Deploy Django
This guide will help you deploy a Django application to Deployxa.
Overview
Django is a high-level Python web framework for building robust web applications. Deployxa provides optimized deployments for Django with automatic configuration.
Features:
- Automatic framework detection
- Python 3.8+ support
- PostgreSQL and MySQL support
- Static file collection
- Database migrations
- Gunicorn WSGI server
- Automatic HTTPS
Prerequisites
- A Django application (version 3.2 or higher recommended)
- A GitHub repository with your code
- A Deployxa account
- PostgreSQL or MySQL database
Quick Start
1. Create Your Django App
If you don't have a Django app yet:
pip install django
django-admin startproject myproject
cd myproject
2. Configure for Production
Update settings.py:
import os
# Security
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = ['your-app.deployxa.app', 'example.com']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT', '5432'),
}
}
# Static files
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Security settings
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
3. Create requirements.txt
pip freeze > requirements.txt
Ensure it includes:
Django>=4.2
gunicorn>=21.2.0
psycopg2-binary>=2.9.9
whitenoise>=6.5.0
4. Push to GitHub
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/myproject.git
git push -u origin main
5. Deploy to Deployxa
- Go to Deployxa Dashboard
- Click "New Project"
- Select your GitHub repository
- Deployxa will automatically detect Django
- Click "Deploy"
Your app will be live in under 60 seconds!
Configuration
Detected Settings
Deployxa automatically detects these settings:
| Setting | Value |
|---|---|
| Framework | Django |
| Build Command | pip install -r requirements.txt |
| Output Directory | staticfiles |
| Start Command | gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 |
| Port | 8000 |
Custom Configuration
If you need to customize settings:
- Go to Project → Settings → Build
- Modify settings as needed
- Save changes
Example Custom Settings:
{
"buildCommand": "pip install -r requirements.txt && python manage.py collectstatic --noinput",
"outputDirectory": "staticfiles",
"startCommand": "gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 --workers 3"
}
Environment Variables
Adding Environment Variables
- Go to Project → Environment
- Click "Add Variable"
- Enter key and value
- Click "Save"
Required Django Environment Variables:
SECRET_KEY=your-secret-key-here
DEBUG=False
ALLOWED_HOSTS=your-app.deployxa.app,example.com
# Database
DB_NAME=your-database
DB_USER=your-username
DB_PASSWORD=your-password
DB_HOST=your-db-host
DB_PORT=5432
# Email (optional)
EMAIL_HOST=smtp.example.com
EMAIL_PORT=587
EMAIL_HOST_USER=your-email
EMAIL_HOST_PASSWORD=your-password
EMAIL_USE_TLS=True
Generating SECRET_KEY
Generate a new secret key:
from django.core.management.utils import get_random_secret_key
print(get_random_secret_key())
Or use Python:
python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'
Database Configuration
Using Managed Database
- Go to Project → Settings → Database
- Click "Create Database"
- Choose PostgreSQL (recommended)
- Configure database settings
- Copy connection details to environment variables
Database Migrations
Run migrations automatically on deployment:
Option 1: Post-Deploy Script
Create a deployment script:
#!/bin/bash
python manage.py migrate --noinput
python manage.py collectstatic --noinput
Option 2: Manual Migration
Run migrations via SSH or console:
python manage.py migrate --noinput
Database Backups
Deployxa automatically backs up managed databases:
- Daily backups
- 7-day retention
- Point-in-time recovery
Static Files
Collecting Static Files
Django requires static files to be collected:
python manage.py collectstatic --noinput
This command is automatically run by Deployxa during deployment.
Serving Static Files
Using WhiteNoise (Recommended):
Add to requirements.txt:
whitenoise>=6.5.0
Update settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ... other middleware
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Using External Storage:
For production, consider using external storage:
Amazon S3:
pip install django-storages boto3
Update settings.py:
INSTALLED_APPS = [
# ...
'storages',
]
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_BUCKET')
AWS_S3_REGION_NAME = os.environ.get('AWS_REGION', 'us-east-1')
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'
Custom Domains
Adding a Custom Domain
- Go to Project → Domains
- Click "Add Domain"
- Enter your domain (e.g.,
example.com) - Configure DNS records
- Wait for verification
DNS Configuration
For Apex Domain (example.com):
Type: A
Name: @
Value: 76.76.21.21
For Subdomain (www.example.com):
Type: CNAME
Name: www
Value: cname.deployxa.com
Update ALLOWED_HOSTS
Update your ALLOWED_HOSTS setting:
ALLOWED_HOSTS = ['your-app.deployxa.app', 'example.com', 'www.example.com']
Or use environment variable:
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')
Performance Optimization
Enable Gunicorn Workers
Configure Gunicorn workers based on CPU cores:
gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 --workers 3
Formula: (2 x CPU_CORES) + 1
Enable Database Connection Pooling
Use connection pooling for better performance:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'CONN_MAX_AGE': 600, # 10 minutes
# ... other settings
}
}
Enable Caching
Configure Django caching:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': os.environ.get('REDIS_URL'),
}
}
Optimize Database Queries
Use Django's optimization tools:
# Use select_related for foreign keys
articles = Article.objects.select_related('author').all()
# Use prefetch_related for many-to-many
authors = Author.objects.prefetch_related('articles').all()
Monitoring
Viewing Logs
- Go to Project → Logs
- Select log type:
- Build Logs: Deployment process
- Runtime Logs: Application output
- Error Logs: Application errors
Django Logging
Configure logging in settings.py:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'INFO',
'propagate': False,
},
},
}
Monitoring Metrics
- Go to Project → Analytics
- View metrics:
- Request count
- Response times
- Error rates
- Bandwidth usage
- CPU/RAM usage
Health Checks
Deployxa automatically monitors your application:
- HTTP health checks every 30 seconds
- Automatic restart on failure
- Alerts on consecutive failures
Troubleshooting
500 Internal Server Error
Problem: Application returns 500 error
Solution:
- Check runtime logs for errors
- Verify environment variables
- Check database connection
- Ensure SECRET_KEY is set
- Check ALLOWED_HOSTS configuration
Static Files Not Loading
Problem: Static files return 404
Solution:
- Run
python manage.py collectstatic --noinput - Verify STATIC_ROOT is set correctly
- Check WhiteNoise is installed and configured
- Ensure DEBUG is False in production
Database Connection Failed
Problem: django.db.utils.OperationalError
Solution:
- Verify database credentials
- Check database host and port
- Ensure database exists
- Check firewall rules
- Verify database user permissions
Migration Failed
Problem: python manage.py migrate fails
Solution:
- Check database connection
- Verify migration files
- Check for syntax errors
- Run migrations locally first
- Check database permissions
ALLOWED_HOSTS Error
Problem: Invalid HTTP_HOST header
Solution:
- Add your domain to ALLOWED_HOSTS
- Use environment variable for ALLOWED_HOSTS
- Include both apex and www domains
- Redeploy after updating
Best Practices
Project Structure
myproject/
├── myproject/
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
├── app/
│ ├── models.py
│ ├── views.py
│ ├── urls.py
│ └── templates/
├── static/
├── templates/
├── manage.py
├── requirements.txt
├── .env.example
└── README.md
Environment Variables
- Never commit
.envfile - Use
.env.exampleas template - Rotate SECRET_KEY regularly
- Use different values per environment
Security
- Keep Django updated
- Use HTTPS only
- Set DEBUG=False in production
- Configure ALLOWED_HOSTS
- Use strong SECRET_KEY
- Enable security middleware
- Validate all inputs
- Use parameterized queries
Performance
- Use Gunicorn with multiple workers
- Enable database connection pooling
- Use caching (Redis/Memcached)
- Optimize database queries
- Use CDN for static assets
- Enable compression
Database
- Use migrations for schema changes
- Index frequently queried columns
- Use transactions for complex operations
- Backup database regularly
- Use connection pooling
Advanced Configuration
Custom Gunicorn Configuration
Create gunicorn.conf.py:
bind = '0.0.0.0:8000'
workers = 3
worker_class = 'sync'
timeout = 120
keepalive = 5
max_requests = 1000
max_requests_jitter = 50
accesslog = '-'
errorlog = '-'
loglevel = 'info'
Update start command:
gunicorn myproject.wsgi:application -c gunicorn.conf.py
Celery for Background Tasks
For background tasks, use Celery:
pip install celery redis
Create celery.py:
from celery import Celery
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
Django REST Framework
For API development:
pip install djangorestframework
Update settings.py:
INSTALLED_APPS = [
# ...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
],
}
Examples
Basic Django App
# views.py
from django.http import HttpResponse
def home(request):
return HttpResponse('Hello, Deployxa!')
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
With Database Model
# models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
# views.py
from django.shortcuts import render
from .models import Article
def article_list(request):
articles = Article.objects.all()
return render(request, 'articles.html', {'articles': articles})
API Endpoint
# views.py
from django.http import JsonResponse
from .models import Article
def article_api(request):
articles = list(Article.objects.values())
return JsonResponse({'articles': articles})
Related Topics
Resources
Need Help? Contact support@deployxa.com or join our community Discord.