Skip to main content

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

  1. Go to Deployxa Dashboard
  2. Click "New Project"
  3. Select your GitHub repository
  4. Deployxa will automatically detect Django
  5. Click "Deploy"

Your app will be live in under 60 seconds!

Configuration

Detected Settings

Deployxa automatically detects these settings:

SettingValue
FrameworkDjango
Build Commandpip install -r requirements.txt
Output Directorystaticfiles
Start Commandgunicorn myproject.wsgi:application --bind 0.0.0.0:8000
Port8000

Custom Configuration

If you need to customize settings:

  1. Go to ProjectSettingsBuild
  2. Modify settings as needed
  3. 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

  1. Go to ProjectEnvironment
  2. Click "Add Variable"
  3. Enter key and value
  4. 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

  1. Go to ProjectSettingsDatabase
  2. Click "Create Database"
  3. Choose PostgreSQL (recommended)
  4. Configure database settings
  5. 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

  1. Go to ProjectDomains
  2. Click "Add Domain"
  3. Enter your domain (e.g., example.com)
  4. Configure DNS records
  5. 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

  1. Go to ProjectLogs
  2. 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

  1. Go to ProjectAnalytics
  2. 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:

  1. Check runtime logs for errors
  2. Verify environment variables
  3. Check database connection
  4. Ensure SECRET_KEY is set
  5. Check ALLOWED_HOSTS configuration

Static Files Not Loading

Problem: Static files return 404

Solution:

  1. Run python manage.py collectstatic --noinput
  2. Verify STATIC_ROOT is set correctly
  3. Check WhiteNoise is installed and configured
  4. Ensure DEBUG is False in production

Database Connection Failed

Problem: django.db.utils.OperationalError

Solution:

  1. Verify database credentials
  2. Check database host and port
  3. Ensure database exists
  4. Check firewall rules
  5. Verify database user permissions

Migration Failed

Problem: python manage.py migrate fails

Solution:

  1. Check database connection
  2. Verify migration files
  3. Check for syntax errors
  4. Run migrations locally first
  5. Check database permissions

ALLOWED_HOSTS Error

Problem: Invalid HTTP_HOST header

Solution:

  1. Add your domain to ALLOWED_HOSTS
  2. Use environment variable for ALLOWED_HOSTS
  3. Include both apex and www domains
  4. 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 .env file
  • Use .env.example as 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})

Resources


Need Help? Contact support@deployxa.com or join our community Discord.