django-admin-dashboard / docs /MIGRATION_GUIDE.md
junaidte14's picture
deploying v1
0ad3564
|
Raw History Blame Contribute Delete
8.4 kB
# Migration Guide: React Admin to Django Admin
## Overview
This guide helps you migrate from the React-based admin dashboard to the Django-based admin dashboard without disrupting your FastAPI backend.
## Before You Start
βœ… **What stays the same:**
- FastAPI backend (no changes needed)
- Database schema (Django reads from existing tables)
- API endpoints (remain unchanged)
- User authentication in FastAPI (JWT still works)
βœ… **What changes:**
- Admin interface moves from React (port 3000) to Django (port 8001)
- Session-based auth for admin dashboard (separate from API JWT)
- Server-side rendering instead of SPA
## Migration Steps
### Phase 1: Setup Django Admin (No Downtime)
**1. Install Django admin alongside existing React app:**
```bash
# In your project root
cd backend/
git clone <django-admin-repo> django_admin
cd django_admin
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```
**2. Configure environment:**
```bash
cp .env.example .env
# Edit .env with your existing database credentials
nano .env
```
**3. Create Django superuser:**
```bash
python manage.py createsuperuser
# Use same credentials as your existing admin user
```
**4. Start Django admin (different port):**
```bash
python manage.py runserver 8001
```
**5. Test in parallel:**
- React Admin: http://localhost:3000/admin
- Django Admin: http://localhost:8001/
- FastAPI: http://localhost:8000/api/v1
Both admin interfaces work simultaneously!
### Phase 2: Data Verification
**Verify Django can read all data:**
```bash
python manage.py shell
```
```python
from apps.core.models import User, Conversation, Message, Agent
# Check data
print(f"Users: {User.objects.count()}")
print(f"Conversations: {Conversation.objects.count()}")
print(f"Messages: {Message.objects.count()}")
print(f"Agents: {Agent.objects.count()}")
# Test a query
user = User.objects.first()
print(f"First user: {user.username}")
```
### Phase 3: User Migration
**Map existing users to Django admin access:**
```python
# In Django shell
from apps.core.models import User
# Option 1: Grant admin access to specific users
admin_usernames = ['admin', 'john', 'jane']
for username in admin_usernames:
try:
user = User.objects.get(username=username)
user.is_staff = True
user.role = 'admin'
user.save()
print(f"βœ“ Granted admin access to {username}")
except User.DoesNotExist:
print(f"βœ— User {username} not found")
# Option 2: Grant admin access to all existing admins
admins = User.objects.filter(role='admin')
admins.update(is_staff=True)
print(f"βœ“ Granted access to {admins.count()} admins")
```
### Phase 4: Update Nginx Configuration
**Current setup (React + FastAPI):**
```nginx
location /admin/ {
# React admin
proxy_pass http://localhost:3000;
}
location /api/ {
# FastAPI
proxy_pass http://localhost:8000;
}
```
**New setup (Django + FastAPI):**
```nginx
location /admin/ {
# Django admin dashboard
proxy_pass http://localhost:8001;
}
location /api/ {
# FastAPI (unchanged)
proxy_pass http://localhost:8000;
}
location /static/ {
# Django static files
alias /path/to/django_admin/staticfiles/;
}
```
### Phase 5: Cutover
**Zero-downtime cutover:**
1. **Update Nginx config:**
```bash
sudo nano /etc/nginx/sites-available/your-site
# Update proxy_pass for /admin/ to point to 8001
sudo nginx -t
sudo systemctl reload nginx
```
2. **Deploy Django admin service:**
```bash
sudo systemctl enable django-admin
sudo systemctl start django-admin
```
3. **Verify:**
```bash
curl http://localhost:8001/
# Should return Django login page
```
4. **Stop React admin** (after confirming Django works):
```bash
# Stop React dev server or PM2 process
pm2 stop react-admin
```
### Phase 6: Cleanup (Optional)
After confirming Django admin works for 1-2 weeks:
```bash
# Archive React admin code
cd frontend/
tar -czf react-admin-backup-$(date +%Y%m%d).tar.gz admin/
rm -rf admin/
# Remove from package.json if needed
npm uninstall @tanstack/react-query recharts lucide-react
```
## Feature Mapping
### React Components β†’ Django Templates
| React Component | Django Equivalent | Status |
|----------------|-------------------|--------|
| `AdminPanel.tsx` | `templates/dashboard/home.html` | βœ… Ready |
| `AnalyticsDashboard.tsx` | `apps/analytics/views.py` | βœ… Ready |
| `UserManagement.tsx` | `templates/dashboard/users.html` | βœ… Ready |
| `adminListConversations.tsx` | `templates/dashboard/conversations.html` | βœ… Ready |
| `RAGManager.tsx` | `templates/rag/collections.html` | βœ… Ready |
| `AgentList.tsx` | `templates/agents/list.html` | βœ… Ready |
| `Settings.tsx` | `templates/dashboard/settings.html` | βœ… Ready |
### API Calls
React made direct API calls to FastAPI:
```typescript
await apiService.adminListConversations(offset, limit);
```
Django also calls FastAPI (via httpx):
```python
async with httpx.AsyncClient() as client:
response = await client.get(f"{FASTAPI_BASE_URL}/conversations")
```
**No changes needed in FastAPI!**
## Testing Checklist
- [ ] Can login to Django admin
- [ ] Dashboard shows correct statistics
- [ ] User list displays all users
- [ ] Can view conversations
- [ ] RAG collections are visible
- [ ] Agents list shows all agents
- [ ] Can create/edit/delete resources
- [ ] Charts render correctly
- [ ] Pagination works
- [ ] Search/filters work
- [ ] Mobile responsive
## Rollback Plan
If issues occur, rollback is simple:
**1. Revert Nginx:**
```bash
# Change proxy_pass back to React (port 3000)
sudo nano /etc/nginx/sites-available/your-site
sudo nginx -t
sudo systemctl reload nginx
```
**2. Restart React admin:**
```bash
cd frontend/admin
npm start
# or
pm2 start react-admin
```
**3. Stop Django admin:**
```bash
sudo systemctl stop django-admin
```
Everything returns to previous state in ~2 minutes.
## Common Issues & Solutions
### Issue: "User not found" on login
**Solution:** User needs `is_staff=True` or `role='admin'`
```python
user = User.objects.get(username='john')
user.is_staff = True
user.save()
```
### Issue: Static files not loading
**Solution:** Collect static files
```bash
python manage.py collectstatic --noinput
```
### Issue: Can't connect to database
**Solution:** Check credentials match FastAPI
```bash
psql -h localhost -U postgres -d chatbot_db
# If this works, Django should work too
```
### Issue: Charts not rendering
**Solution:** Check Chart.js loaded
```html
<!-- Should be in base.html -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
```
### Issue: FastAPI endpoints timing out
**Solution:** Increase timeout in Django settings
```python
# settings.py
FASTAPI_TIMEOUT = 60 # seconds
```
## Performance Comparison
| Metric | React Admin | Django Admin |
|--------|-------------|--------------|
| Initial Load | ~2-3s (SPA bundle) | ~500ms (SSR) |
| Page Navigation | ~100ms (client) | ~200ms (server) |
| Data Refresh | Real-time | Cache (5min) |
| Memory Usage | ~150MB (browser) | ~50MB (server) |
| Mobile Performance | Good | Excellent |
## Docker Migration
If using Docker, update `docker-compose.yml`:
```yaml
services:
# Remove React admin service
# react_admin:
# build: ./frontend/admin
# ports:
# - "3000:3000"
# Add Django admin service
django_admin:
build: ./backend/django_admin
ports:
- "8001:8001"
depends_on:
- postgres
- fastapi
```
## Post-Migration
**Monitor for 1 week:**
- Check error logs: `tail -f logs/django.log`
- Monitor response times
- Gather user feedback
- Watch for any missing features
**After 2 weeks of stable operation:**
- Remove React admin code
- Update documentation
- Archive old configs
- Celebrate! πŸŽ‰
## Need Help?
Common commands:
```bash
# Check Django admin status
sudo systemctl status django-admin
# View logs
tail -f logs/django.log
journalctl -u django-admin -f
# Restart Django admin
sudo systemctl restart django-admin
# Check database connection
python manage.py dbshell
# Clear cache
python manage.py shell
>>> from django.core.cache import cache
>>> cache.clear()
```
## Conclusion
This migration:
- βœ… Zero downtime possible
- βœ… Easy rollback
- βœ… No FastAPI changes
- βœ… No database changes
- βœ… Better performance
- βœ… Easier maintenance
- βœ… Production-ready from day 1