How to Set DEBUG False in Production in Django
In Django, set
DEBUG = False in your settings.py file when deploying to production. Also, ensure you configure ALLOWED_HOSTS with your domain names to avoid errors.Syntax
The DEBUG setting is a boolean in Django's settings.py file. Setting it to False disables detailed error pages and debug information, which is important for production security.
The ALLOWED_HOSTS setting is a list of strings representing the host/domain names your Django site can serve. This prevents HTTP Host header attacks.
python
DEBUG = False ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
Example
This example shows a minimal settings.py snippet for production with DEBUG set to False and ALLOWED_HOSTS properly configured.
python
DEBUG = False ALLOWED_HOSTS = ['example.com', 'www.example.com'] # Other production settings like database, static files, etc.
Output
No debug information shown on errors; only allowed hosts can access the site.
Common Pitfalls
- Forgetting to set
DEBUG = Falsein production can expose sensitive debug information to users. - Not setting
ALLOWED_HOSTScorrectly causes Django to raise aDisallowedHosterror. - Leaving
ALLOWED_HOSTS = []or['*']is insecure and should be avoided. - Not configuring static files properly when
DEBUG = Falsecan cause missing CSS or images.
python
## Wrong way (debug on in production) DEBUG = True ALLOWED_HOSTS = [] ## Right way DEBUG = False ALLOWED_HOSTS = ['yourdomain.com']
Quick Reference
| Setting | Purpose | Example Value |
|---|---|---|
| DEBUG | Enable or disable debug mode | False |
| ALLOWED_HOSTS | List of allowed domain names | ['example.com', 'www.example.com'] |
| STATIC_ROOT | Directory for collected static files | '/var/www/example.com/static/' |
| SECRET_KEY | Keep secret in production | 'your-secure-secret-key' |
Key Takeaways
Always set DEBUG = False in production to protect sensitive information.
Configure ALLOWED_HOSTS with your domain names to prevent host header attacks.
Never leave ALLOWED_HOSTS empty or set to wildcard '*' in production.
Remember to properly serve static files when DEBUG is False.
Keep your SECRET_KEY secure and do not expose it in public repositories.