Do These Before Pushing Your Django Application to Production

By Nischal Lamichhane

36 reads 0 comments 8 likes

Do These Before Pushing Your Django Application to Production

Published on April 27, 2025


Before you deploy your Django app to production, it's critical to ensure it's secure, performant, and stable. This guide covers everything you need to configure, disable, enable, or add before going live. Missing any of these steps could lead to serious vulnerabilities or poor performance.


1. Set DEBUG = False

Never run your production site with DEBUG = True. It reveals sensitive information like settings, environment variables, and even passwords if an error occurs.

DEBUG = False

Also, ensure ALLOWED_HOSTS is set properly:

ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']

2. Use a Secure Secret Key

Make sure your SECRET_KEY is not hardcoded in settings.py for production. Instead, load it from environment variables using:

import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

And set it via your server's environment configuration.


3. Serve Static and Media Files Properly

Django doesn’t serve static files in production. Use WhiteNoise for small projects or serve via Nginx for larger ones.

# settings.py
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_ROOT = BASE_DIR / 'media'

Then collect your static files:

python manage.py collectstatic

4. Enable Security Middleware and Headers

Django has built-in security middleware. Enable the following settings:

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'

Make sure your site uses HTTPS with a valid SSL certificate.


5. Configure Logging

In production, you want to log errors to a file or a logging service:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': '/var/log/django/errors.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

6. Set Up Allowed Hosts and CORS (if needed)

Make sure only your domain is allowed to access the app:

ALLOWED_HOSTS = ['yourdomain.com']

If you're using APIs and accessing them from different domains, configure django-cors-headers properly.


7. Database Configuration

Use PostgreSQL or another production-ready database. Make sure your database credentials are stored securely in environment variables.

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': 'localhost',
        'PORT': '',
    }
}

8. Turn Off Django Admin (Optional but Recommended)

Consider limiting access to the Django admin using IP allowlists, a VPN, or even disabling it altogether if not needed.


9. Install Gunicorn or uWSGI

Django’s development server is not suitable for production. Use Gunicorn or uWSGI behind a web server like Nginx:

pip install gunicorn

Then run:

gunicorn yourproject.wsgi:application

10. Run check and migrate

Before deployment, run Django’s system checks:

python manage.py check

Then apply migrations:

python manage.py migrate --noinput

11. Monitor Performance and Errors

Use services like Sentry, Rollbar, or Prometheus to monitor logs and performance. Also consider setting up health checks and uptime monitoring.


12. Configure Email Backend

Set up SMTP settings for email notifications, password resets, and error emails:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.yourmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')

13. Backups and Rollbacks

Before you go live, automate database and media backups. Store them offsite or in a cloud bucket. Always have a rollback plan in case a new release breaks something.


14. Use a CDN

For faster static file delivery, consider using a CDN like Cloudflare or AWS CloudFront. This can drastically improve page load times.


15. Test Everything!

  • Test in staging before production.
  • Run functional and unit tests.
  • Check responsiveness, media uploads, and error pages.
  • Ensure HTTPS and secure headers are properly working.

Conclusion

Production deployment is not just about pushing code; it's about building a safe, fast, and scalable environment for your users. Carefully go through each of these steps before launching your Django project to avoid regrets later.

Once you've done all this, take a deep breath — you're ready to go live!

Jump to Table of Contents

Comments

You must be logged in to post a comment.


No comments yet. Be the first to comment!

Also Read

Mastering Python Command-Line Arguments: A Comprehensive Guide
Mastering Python Command-Line Arguments: A Comprehensive Guide

Learn how to use Python command-line arguments effectively to automate tasks, streamline workflows,…

Create the viral Ghibli Art for FREE
Create the viral Ghibli Art for FREE

How to create your own Ghibli Art for Free!

Integrate HTMX with Django: A Modern Alternative to ReactJS
Integrate HTMX with Django: A Modern Alternative to ReactJS

Discover how to integrate HTMX with Django to build modern, interactive web applications. Learn to …

Deploying Django Apps for Free on PythonAnywhere: Step-by-Step Guide
Deploying Django Apps for Free on PythonAnywhere: Step-by-Step Guide

Learn how to deploy Django apps for free on PythonAnywhere with this step-by-step guide. From proje…

Flask Vs Django
Flask Vs Django

This article provides a comprehensive comparison between Flask and Django, two prominent Python web…

Python Heap - Complete Guide to Heap Data Structures in Python
Python Heap - Complete Guide to Heap Data Structures in Python

Learn everything about Python Heap, including heap data structures, the heapq module, min-heaps, ma…