0
0
DjangoHow-ToBeginner · 3 min read

How to Set Debug Mode in Django: Simple Guide

To set debug mode in Django, open your settings.py file and set the DEBUG variable to True to enable debug mode or False to disable it. This controls whether detailed error pages and debugging information are shown during development.
📐

Syntax

The debug mode in Django is controlled by the DEBUG setting in the settings.py file.

  • DEBUG = True: Enables debug mode, showing detailed error pages and extra debugging information.
  • DEBUG = False: Disables debug mode, hiding detailed errors and showing generic error pages for security.
python
DEBUG = True
💻

Example

This example shows how to set debug mode in a Django project's settings.py file. When DEBUG is True, Django will display detailed error messages in the browser if something goes wrong.

python
import os

# settings.py

DEBUG = True  # Turn on debug mode for development

ALLOWED_HOSTS = []  # Empty list means all hosts are allowed in debug mode

# Example usage in a view (for demonstration only)
from django.http import HttpResponse

def example_view(request):
    # This will raise an error if DEBUG is True, showing detailed info
    return HttpResponse(1 / 0)  # Division by zero error
Output
If DEBUG=True, visiting the view shows a detailed error page with traceback. If DEBUG=False, visiting the view shows a generic 500 error page.
⚠️

Common Pitfalls

Common mistakes when setting debug mode include:

  • Leaving DEBUG = True in production, which exposes sensitive information.
  • Not setting ALLOWED_HOSTS properly when DEBUG = False, causing errors.
  • Changing DEBUG without restarting the server, so changes don't take effect.
python
## Wrong (production with debug on)
DEBUG = True
ALLOWED_HOSTS = []  # This is insecure for production

## Right (production safe)
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
📊

Quick Reference

SettingDescription
DEBUG = TrueShow detailed error pages and debugging info (use in development only)
DEBUG = FalseHide detailed errors, show generic error pages (use in production)
ALLOWED_HOSTS = []Allow all hosts (only safe if DEBUG=True)
ALLOWED_HOSTS = ['example.com']Allow only specified hosts (required if DEBUG=False)

Key Takeaways

Set DEBUG = True in settings.py to enable debug mode during development.
Always set DEBUG = False in production to protect sensitive information.
Configure ALLOWED_HOSTS properly when DEBUG is False to avoid errors.
Restart the Django server after changing the DEBUG setting for changes to apply.
Never leave DEBUG = True on a public-facing production site.