This document explains the architectural decisions made in the AI Usage Learning Platform and how they satisfy the functional and non-functional requirements.
┌─────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ (Django Templates + Bootstrap 5 + Chart.js) │
│ - Login/Register │
│ - Dashboard with visualizations │
│ - Usage logging forms │
│ - Insights display │
│ - Feedback forms │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Application Layer │
│ (Django Views + Forms) │
│ - Authentication (login, register, logout) │
│ - Dashboard data aggregation │
│ - Usage log management │
│ - Insight generation │
│ - Feedback handling │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Business Logic Layer │
│ (Models + Signals) │
│ - UserProfile (extended user data) │
│ - AIUsageLog (usage tracking) │
│ - AIEthicsPolicy (compliance rules) │
│ - ComplianceStatus (compliance evaluation) │
│ - UserInsight (automated insights) │
│ - UserFeedback (user feedback) │
│ - Signals (auto profile creation, insight generation) │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Data Layer │
│ (Django ORM + SQLite) │
│ - User authentication data │
│ - AI usage logs │
│ - Policies and compliance data │
│ - Insights and feedback │
└─────────────────────────────────────────────────────────────┘
Why: Django's standard pattern ensures separation of concerns.
- Models: Data structure and business logic
- Views: Request handling and data processing
- Templates: Presentation logic
Why: Abstracts database operations and makes the code database-agnostic.
Example:
AIUsageLog.objects.filter(user=user).order_by('-timestamp')Why: Automatically trigger actions when certain events occur.
Example:
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)Why: Centralized validation and security.
Example:
class AIUsageLogForm(forms.ModelForm):
class Meta:
model = AIUsageLog
fields = [...]User (Django Auth)
│
├─── 1:1 ──→ UserProfile
│
├─── 1:N ──→ AIUsageLog
│ │
│ └─── N:1 ──→ AIEthicsPolicy
│
├─── 1:N ──→ ComplianceStatus
│ │
│ └─── N:1 ──→ AIEthicsPolicy
│
├─── 1:N ──→ UserInsight
│ │
│ └─── N:M ──→ AIUsageLog (related_usage_logs)
│
└─── 1:N ──→ UserFeedback
-
UserProfile extends User: Keeps authentication separate from profile data (Single Responsibility Principle)
-
AIEthicsPolicy is independent: Allows multiple versions and policies to coexist
-
AIUsageLog references Policy: Tracks which policy was active at the time of usage
-
ComplianceStatus is calculated: Periodic snapshots of compliance for historical tracking
-
UserInsight can reference logs: Allows detailed insights based on specific usage patterns
Implementation:
dashboard_view()aggregates user-specific data- User-filtered queries:
AIUsageLog.objects.filter(user=request.user) - Statistics: total, today, week, month usage counts
- Compliance percentage calculation
Files:
- views.py -
dashboard_view() - dashboard.html
Implementation:
- Chart.js integration in base template
- Three chart types:
- Line chart: Daily usage trend (30 days)
- Pie chart: Usage by AI tool
- Bar chart: Usage by type
- Data passed as JSON from Django to JavaScript
Files:
- dashboard.html - Chart rendering
Implementation:
- UserFeedback model with file upload support
- Status tracking workflow
- Admin panel for reviewing feedback
Files:
- models.py -
UserFeedback - views.py -
feedback_view() - feedback.html
Implementation:
- AIEthicsPolicy model with versioning
- Admin interface for CRUD operations
- Active policy detection with date ranges
- Compliance evaluation against policies
Files:
Implementation:
- Django authentication system
- Login, register, logout views
- Login required decorator for protected views
- Session management
Files:
Implementation:
- Automated insight generation via signals
- Different insight types: patterns, compliance, achievements, warnings
- Priority-based display
- Read/dismiss functionality
Files:
- models.py -
UserInsight - signals.py - Automatic generation
- insights.html
Implementation:
- Bootstrap 5 for responsive, professional UI
- Intuitive navigation with sidebar
- Clear visual hierarchy
- Contextual help text
- Error messages and success confirmations
Evidence: Consistent UI patterns, clear calls-to-action, minimal clicks to complete tasks
Implementation:
- Consent Tracking:
data_collection_consentfield with timestamp - Data Access: Users can view all their data via dashboard
- Data Export: JSON export of all user data (
export_data_view) - Data Deletion: Cascade delete on user removal
- Privacy Controls: Granular settings for analytics and notifications
- Transparency: Clear privacy information in profile
Files:
- models.py - Consent fields
- views.py -
export_data_view() - profile.html - Privacy controls
Why: Prevents cross-site request forgery attacks
How: Django's CSRF middleware + {% csrf_token %} in forms
Why: Protects user accounts How: Django's password validators + hashing (PBKDF2)
Why: Prevents database attacks How: Django ORM automatically parameterizes queries
Why: Prevents script injection How: Django template auto-escaping
Why: Protects user sessions How: HTTPOnly cookies, SameSite flag, 2-hour timeout
Why: Protects sensitive views
How: @login_required on all dashboard views
Why:
- Mature, battle-tested framework
- Excellent ORM for database operations
- Built-in authentication and admin
- Strong security features
- Large ecosystem and community
Alternatives Considered: Flask (too minimal), FastAPI (REST-focused)
Why:
- Zero configuration
- Perfect for development and small deployments
- Single file database (easy backup)
- Can migrate to PostgreSQL later
Production Alternative: PostgreSQL for better concurrency
Why:
- Professional UI components
- Responsive out of the box
- Extensive documentation
- No build process needed
Alternatives Considered: Tailwind (requires build), Material UI (heavier)
Why:
- Lightweight (64KB)
- Beautiful, responsive charts
- Simple API
- No jQuery dependency
Alternatives Considered: D3.js (steeper learning curve), Plotly (heavier)
- Suitable for: 100-1000 users
- Database: SQLite (up to ~100 concurrent users)
- Storage: File system for uploads
If needed to scale to 10,000+ users:
-
Database: Migrate to PostgreSQL
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # ... } }
-
Caching: Add Redis for session storage and query caching
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', } }
-
File Storage: Move to cloud storage (S3, Azure Blob)
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
-
Load Balancing: Deploy multiple application servers behind nginx
-
Database Optimization: Add indexes, use select_related/prefetch_related
AIUsageLog.objects.select_related('user', 'policy').filter(...)
- Model methods (compliance checking, validation)
- Form validation
- Signal handlers
- View responses
- Authentication flow
- Dashboard data aggregation
- User registration and login
- Dashboard displays correct data
- Charts render properly
- Usage logging works
- Compliance calculation is accurate
- Insights are generated
- Feedback submission works
- Data export works
- Admin panel is functional
-
Database Indexes: On frequently queried fields
indexes = [ models.Index(fields=['user', '-timestamp']), ]
-
Query Optimization: Limit results in recent activity
recent_logs = AIUsageLog.objects.filter(user=user)[:10]
-
Pagination: For usage history (25 per page)
-
Chart Data Limiting: Last 30 days only for trend chart
- Query result caching
- Database connection pooling
- Static file CDN
- Lazy loading for images
- Background tasks for insight generation (Celery)
Example: Add a new AI tool
-
Update model choices:
AI_TOOL_CHOICES = [ # ... existing ('new_tool', 'New AI Tool'), ]
-
Create and run migration:
python manage.py makemigrations python manage.py migrate
-
No template changes needed (dynamic rendering)
dashboard/
├── models.py # Data models (single source of truth)
├── views.py # Request handlers (business logic)
├── forms.py # Form validation (input handling)
├── urls.py # URL routing (API endpoints)
├── admin.py # Admin configuration (management)
├── signals.py # Event handlers (automation)
└── tests.py # Test cases (quality assurance)
Benefits:
- Clear separation of concerns
- Easy to locate functionality
- Maintainable and testable
Before production deployment:
- Set
DEBUG = False - Change
SECRET_KEY - Configure
ALLOWED_HOSTS - Use PostgreSQL/MySQL
- Set up HTTPS
- Configure email backend
- Set up logging
- Use environment variables
- Run
collectstatic - Set up automated backups
- Configure error monitoring (Sentry)
- Load test the application
This architecture provides:
- ✅ Clean separation of concerns
- ✅ Scalability path
- ✅ Security by default
- ✅ Easy maintenance
- ✅ GDPR compliance
- ✅ Comprehensive testing
- ✅ Professional user experience
The design supports all functional requirements while maintaining code quality and extensibility.