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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# Django Admin Dashboard - Setup & Deployment Guide

## Quick Start

### 1. Prerequisites
```bash
# System requirements
- Python 3.11+
- PostgreSQL 14+
- Redis 7+
- Node.js 18+ (for Tailwind CSS compilation in production)
```

### 2. Installation

```bash
# Clone or navigate to project
cd django_admin_backend

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Copy environment file
cp .env.example .env

# Edit .env with your database credentials
nano .env
```

### 3. Database Setup

```bash
# The Django admin uses the SAME database as your FastAPI app
# No need to create a new database

# Create Django tables (managed models only - won't touch FastAPI tables)
python manage.py migrate

# Create superuser for Django admin
python manage.py createsuperuser
```

### 4. Create Required Directories

```bash
mkdir -p logs staticfiles media
```

### 5. Run Development Server

```bash
# Start Django admin dashboard
python manage.py runserver 8001

# In another terminal, start your FastAPI app
cd ../fastapi_app
uvicorn main:app --reload --port 8000
```

Now access:
- **Admin Dashboard**: http://localhost:8001/
- **Django Admin**: http://localhost:8001/admin/
- **FastAPI**: http://localhost:8000/api/v1/

---

## Project Structure

```
django_admin_backend/
β”œβ”€β”€ manage.py
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .env
β”œβ”€β”€ .env.example
β”‚
β”œβ”€β”€ config/                    # Django configuration
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”‚
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ core/                  # Core models & auth
β”‚   β”‚   β”œβ”€β”€ models.py         # User, Conversation, Message, etc.
β”‚   β”‚   β”œβ”€β”€ admin.py          # Django admin config
β”‚   β”‚   β”œβ”€β”€ views.py          # Auth views
β”‚   β”‚   └── urls/
β”‚   β”‚       └── auth.py
β”‚   β”‚
β”‚   β”œβ”€β”€ dashboard/            # Main dashboard
β”‚   β”‚   β”œβ”€β”€ views.py
β”‚   β”‚   └── urls.py
β”‚   β”‚
β”‚   β”œβ”€β”€ analytics/            # Analytics module
β”‚   β”‚   β”œβ”€β”€ views.py
β”‚   β”‚   └── urls.py
β”‚   β”‚
β”‚   β”œβ”€β”€ rag/                  # RAG management
β”‚   β”‚   β”œβ”€β”€ views.py
β”‚   β”‚   └── urls.py
β”‚   β”‚
β”‚   └── agents/               # Agent management
β”‚       β”œβ”€β”€ views.py
β”‚       └── urls.py
β”‚
β”œβ”€β”€ templates/                # HTML templates
β”‚   β”œβ”€β”€ base.html
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   └── login.html
β”‚   β”œβ”€β”€ dashboard/
β”‚   β”‚   β”œβ”€β”€ home.html
β”‚   β”‚   β”œβ”€β”€ users.html
β”‚   β”‚   └── conversations.html
β”‚   β”œβ”€β”€ rag/
β”‚   β”‚   └── collections.html
β”‚   └── agents/
β”‚       β”œβ”€β”€ list.html
β”‚       └── detail.html
β”‚
β”œβ”€β”€ static/                   # Static files (CSS, JS, images)
β”œβ”€β”€ staticfiles/              # Collected static files (production)
β”œβ”€β”€ media/                    # User uploads
└── logs/                     # Application logs
```

---

## Configuration

### Database Settings

Django reads from the **same PostgreSQL database** as FastAPI. The models are defined as `managed = False`, meaning Django will:
- βœ… Read data from existing tables
- βœ… Write new data to tables
- ❌ NOT create or modify table schemas

### Environment Variables

```bash
# Required
SECRET_KEY=            # Generate with: python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
DB_NAME=               # Same as FastAPI
DB_USER=               # Same as FastAPI
DB_PASSWORD=           # Same as FastAPI
DB_HOST=               # Usually localhost
DB_PORT=               # Usually 5432

# Optional
DEBUG=False            # Set to False in production
REDIS_URL=             # For caching
FASTAPI_BASE_URL=      # For calling FastAPI endpoints
SENTRY_DSN=            # For error tracking
```

---

## Production Deployment

### Option 1: Separate Server (Recommended)

#### Nginx Configuration

```nginx
# /etc/nginx/sites-available/admin-dashboard

# FastAPI
server {
    listen 80;
    server_name api.yourdomain.com;

    location /api/v1/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

# Django Admin Dashboard
server {
    listen 80;
    server_name admin.yourdomain.com;

    location /static/ {
        alias /var/www/django_admin/staticfiles/;
        expires 30d;
    }

    location /media/ {
        alias /var/www/django_admin/media/;
        expires 7d;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

#### Systemd Service Files

**FastAPI Service** (`/etc/systemd/system/fastapi.service`):
```ini
[Unit]
Description=FastAPI Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/fastapi_app
Environment="PATH=/var/www/fastapi_app/venv/bin"
ExecStart=/var/www/fastapi_app/venv/bin/uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

[Install]
WantedBy=multi-user.target
```

**Django Admin Service** (`/etc/systemd/system/django-admin.service`):
```ini
[Unit]
Description=Django Admin Dashboard
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/django_admin
Environment="PATH=/var/www/django_admin/venv/bin"
ExecStart=/var/www/django_admin/venv/bin/gunicorn config.wsgi:application --bind 0.0.0.0:8001 --workers 3

[Install]
WantedBy=multi-user.target
```

#### Deployment Steps

```bash
# 1. Clone to server
cd /var/www
git clone <your-repo> django_admin
cd django_admin

# 2. Setup virtual environment
python3.11 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# 3. Configure environment
cp .env.example .env
nano .env  # Edit with production values

# 4. Collect static files
python manage.py collectstatic --noinput

# 5. Create log directory
mkdir -p logs
chown www-data:www-data logs

# 6. Start services
sudo systemctl enable django-admin
sudo systemctl start django-admin
sudo systemctl enable fastapi
sudo systemctl start fastapi

# 7. Configure Nginx
sudo ln -s /etc/nginx/sites-available/admin-dashboard /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

# 8. Setup SSL with Let's Encrypt
sudo certbot --nginx -d admin.yourdomain.com
sudo certbot --nginx -d api.yourdomain.com
```

---

### Option 2: Single Server with Path-Based Routing

```nginx
server {
    listen 80;
    server_name yourdomain.com;

    # FastAPI API
    location /api/v1/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
    }

    # Django Admin Dashboard
    location /admin/ {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
    }

    # Django static files
    location /static/ {
        alias /var/www/django_admin/staticfiles/;
    }
}
```

---

## Docker Deployment

### docker-compose.yml

```yaml
version: '3.8'

services:
  postgres:
    image: postgres:16
    environment:
      POSTGRES_DB: chatbot_db
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: your_password
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  fastapi:
    build: ./fastapi_app
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
    ports:
      - "8000:8000"
    depends_on:
      - postgres
      - redis
    environment:
      DATABASE_URL: postgresql://postgres:your_password@postgres:5432/chatbot_db

  django_admin:
    build: ./django_admin_backend
    command: gunicorn config.wsgi:application --bind 0.0.0.0:8001 --workers 3
    ports:
      - "8001:8001"
    depends_on:
      - postgres
      - redis
      - fastapi
    environment:
      DB_HOST: postgres
      DB_NAME: chatbot_db
      DB_USER: postgres
      DB_PASSWORD: your_password
      REDIS_URL: redis://redis:6379/1
      FASTAPI_BASE_URL: http://fastapi:8000/api/v1

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./staticfiles:/var/www/static
    depends_on:
      - fastapi
      - django_admin

volumes:
  postgres_data:
```

### Dockerfile for Django Admin

```dockerfile
FROM python:3.11-slim

WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy project
COPY . .

# Collect static files
RUN python manage.py collectstatic --noinput

# Create logs directory
RUN mkdir -p logs

EXPOSE 8001

CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8001", "--workers", "3"]
```

---

## Common Tasks

### Create Superuser
```bash
python manage.py createsuperuser
```

### Update Database Models (if you add managed models)
```bash
python manage.py makemigrations
python manage.py migrate
```

### Collect Static Files
```bash
python manage.py collectstatic --noinput
```

### Clear Cache
```bash
python manage.py shell
>>> from django.core.cache import cache
>>> cache.clear()
```

### View Logs
```bash
tail -f logs/django.log
```

---

## User Permissions

### Role-Based Access

1. **Superuser** (`is_superuser=True`)
   - Full Django admin access
   - Full custom dashboard access
   - Can manage users, agents, RAG, everything

2. **Staff/Admin** (`is_staff=True` or `role='admin'`)
   - Custom dashboard access
   - View analytics
   - Manage users (limited)
   - Manage RAG collections
   - Manage agents

3. **Regular User** (future)
   - No admin access
   - Can view own API keys (when implemented)
   - Can manage own agents (when implemented)

### Grant Admin Access to Existing User

```python
# Django shell
python manage.py shell

from apps.core.models import User
user = User.objects.get(username='john')
user.is_staff = True
user.role = 'admin'
user.save()
```

---

## Extending for User Self-Service

When you want to allow users to manage their own resources:

### 1. Create User Dashboard Views

```python
# apps/dashboard/views.py

@login_required
def user_dashboard(request):
    """User-specific dashboard."""
    if request.user.is_staff:
        return redirect('dashboard:home')
    
    # Show user's own data
    user_agents = Agent.objects.filter(created_by_id=request.user.id)
    # ... etc
    
    return render(request, 'user/dashboard.html', {'agents': user_agents})
```

### 2. Add API Key Management

```python
# apps/core/models.py

class APIKey(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, unique=True)
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    last_used = models.DateTimeField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
```

### 3. Update URL Routing

```python
# config/urls.py

urlpatterns = [
    # Admin dashboard (staff only)
    path('admin/', include('apps.dashboard.urls')),
    
    # User dashboard (regular users)
    path('my/', include('apps.user.urls')),
]
```

---

## Monitoring & Maintenance

### Health Check Endpoint

Add to `apps/dashboard/views.py`:

```python
from django.http import JsonResponse
from django.db import connection

def health_check(request):
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
        return JsonResponse({'status': 'healthy'})
    except Exception as e:
        return JsonResponse({'status': 'unhealthy', 'error': str(e)}, status=500)
```

### Performance Monitoring

Use Django Debug Toolbar in development:
```python
# Already configured in settings.py when DEBUG=True
# Access at: http://localhost:8001/__debug__/
```

### Error Tracking

Sentry is configured. Add DSN to `.env`:
```bash
SENTRY_DSN=https://your-sentry-dsn
ENVIRONMENT=production
```

---

## Security Checklist

- [ ] `DEBUG=False` in production
- [ ] Strong `SECRET_KEY` generated and kept secret
- [ ] `ALLOWED_HOSTS` configured properly
- [ ] SSL/HTTPS enabled
- [ ] Database credentials secured
- [ ] Redis password set (if exposed)
- [ ] CORS configured correctly
- [ ] CSP headers configured
- [ ] Regular security updates: `pip list --outdated`
- [ ] Firewall configured (only ports 80, 443 open)
- [ ] Backup strategy in place

---

## Troubleshooting

### Can't login to admin
```bash
# Reset user password
python manage.py shell
>>> from apps.core.models import User
>>> user = User.objects.get(username='admin')
>>> user.set_password('newpassword')
>>> user.save()
```

### Database connection errors
```bash
# Check database connectivity
python manage.py dbshell
# Or
psql -h localhost -U postgres -d chatbot_db
```

### Static files not loading
```bash
python manage.py collectstatic --clear --noinput
```

### 502 Bad Gateway
```bash
# Check if Django is running
sudo systemctl status django-admin
# Check logs
journalctl -u django-admin -f
```

---

## Support

For issues or questions:
1. Check logs: `tail -f logs/django.log`
2. Check system logs: `journalctl -u django-admin -f`
3. Enable DEBUG mode temporarily to see detailed errors
4. Check database connectivity
5. Verify FastAPI is running and accessible

---

## License & Credits

Built with Django 5.0, Tailwind CSS, Alpine.js, and Chart.js.