Configuring settings.py for Production in Django


When deploying a Django project to production, it's important to configure your settings.py file properly to ensure security, performance, and stability. In this article, we will go through the essential steps and best practices for configuring your Django settings for a production environment.

1. Setting DEBUG to False

In development, Django's DEBUG setting is typically set to True, which provides helpful debugging information and error pages. However, in production, you should always set DEBUG to False to prevent sensitive information from being exposed to users.

            
    DEBUG = False
            
        

Additionally, set ALLOWED_HOSTS to define the list of allowed hostnames or IP addresses that can serve your site:

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

Setting ALLOWED_HOSTS helps protect against HTTP Host header attacks.

2. Configure Database Settings

In production, you should use a robust database like PostgreSQL, MySQL, or another production-grade database. Django's default database is SQLite, which is not suitable for production environments. Here’s an example of how to configure PostgreSQL in production:

            
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'yourdbname',
            'USER': 'yourdbuser',
            'PASSWORD': 'yourdbpassword',
            'HOST': 'localhost',
            'PORT': '5432',
        }
    }
            
        

Make sure to replace yourdbname, yourdbuser, and yourdbpassword with the appropriate values for your database.

3. Enable Secure Cookies

In production, it's crucial to secure your cookies to protect users' sessions. Enable the following settings:

            
    SESSION_COOKIE_SECURE = True  # Ensures cookies are only sent over HTTPS
    CSRF_COOKIE_SECURE = True    # Ensures CSRF cookie is only sent over HTTPS
            
        

These settings ensure that the session and CSRF cookies are transmitted securely over HTTPS, preventing interception by attackers.

4. Configure SECRET_KEY

The SECRET_KEY is one of the most important security settings in Django. It is used for cryptographic signing and should be kept secret. In production, you should store your SECRET_KEY in an environment variable or a separate settings file, rather than hardcoding it in settings.py.

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

Then, set the DJANGO_SECRET_KEY environment variable on your production server:

            
    export DJANGO_SECRET_KEY='your-production-secret-key'
            
        

Make sure to generate a strong, unique secret key for your production environment.

5. Set Up Static and Media Files

In production, you need to configure Django to serve static files and media files properly. For static files, you can use a dedicated server like Nginx or a cloud service. In settings.py, set the following:

            
    STATIC_URL = '/static/'

    # For production, set the STATIC_ROOT directory where static files will be collected
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
            
        

For media files (uploaded by users), configure the following:

            
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
            
        

Run python manage.py collectstatic to gather all static files into the STATIC_ROOT directory for serving in production.

6. Set Up Logging

In a production environment, it's essential to log errors and important events for monitoring and debugging purposes. Django provides a built-in logging system that you can configure in your settings.py file. Here’s an example of basic logging configuration:

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

This configuration logs errors to a file called errors.log. You can customize this to log to different locations, like a cloud logging service, or log different levels (e.g., INFO, WARNING, etc.).

7. Set SECURE_SSL_REDIRECT

To ensure that your website is always accessed securely over HTTPS, enable the SECURE_SSL_REDIRECT setting. This redirects all HTTP requests to HTTPS:

            
    SECURE_SSL_REDIRECT = True
            
        

In addition, enable the SECURE_HSTS_SECONDS setting to instruct browsers to only communicate with your site over HTTPS for a specific period:

            
    SECURE_HSTS_SECONDS = 31536000  # One year
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True  # Apply to all subdomains
    SECURE_HSTS_PRELOAD = True  # Add to HSTS preload list
            
        

8. Enable X-Content-Type-Options and Other Security Headers

For additional security, set the X-Content-Type-Options and other headers to protect against MIME-type sniffing and ensure secure connections:

            
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_BROWSER_XSS_FILTER = True
    X_FRAME_OPTIONS = 'DENY'  # Prevent your site from being embedded in an iframe
            
        

9. Set Up Email Settings for Production

In production, Django will need to send emails (for example, when a user resets their password). Configure your email backend settings to use a real email provider:

            
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_HOST = 'smtp.yourmailprovider.com'
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True
    EMAIL_HOST_USER = 'your-email@example.com'
    EMAIL_HOST_PASSWORD = 'your-email-password'
    DEFAULT_FROM_EMAIL = 'webmaster@yourdomain.com'
            
        

Ensure to replace the values with your actual email provider's details.

10. Final Checks and Security Practices

  • Ensure that django.contrib.staticfiles is included in INSTALLED_APPS in settings.py for managing static files.
  • Use a web server like Nginx or Apache to serve static files and act as a reverse proxy for your Django app.
  • Make sure your database is configured with the appropriate credentials and that it's only accessible from the server where Django is running.
  • Check for any unnecessary or insecure middleware that may be enabled in your production settings.

Conclusion

Configuring Django for production requires careful attention to security, performance, and scalability. By following the steps above, you can ensure your Django application is ready for a production environment. Always remember to test your production configuration thoroughly and regularly monitor your application's health and performance.





Advertisement