Debugging Django Errors
Debugging is the search for the cause of an error. Django helps with a debug page that shows what went wrong.
Turn DEBUG on
This line lives in settings.py. True turns the debug pages on.
DEBUG = TrueA view with a mistake
This view divides by zero. A division by zero is an error in Python.
def broken(request):
return 1 / 0Ask the broken page
The test client asks for the broken page. The prints show the 500 status and the debug page.
client = Client(raise_request_exception=False)
response = client.get("/broken/")
print(response.status_code)
print("Traceback" in response.content.decode())Ask for a missing page
The debug page for a missing address lists the tried addresses. The prints show the 404 status and that list.
response = client.get("/nope/")
print(response.status_code)
print("Using the URLconf" in response.content.decode())Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django.http import HttpResponse
from django.urls import path
def home(request):
return HttpResponse("Home page")
def broken(request):
return 1 / 0
urlpatterns = [path("", home), path("broken/", broken)]
from django.test import Client
client = Client(raise_request_exception=False)
print(client.get("/").status_code)
response = client.get("/broken/")
print(response.status_code)
print("Traceback" in response.content.decode())
response = client.get("/nope/")
print(response.status_code)
print("Using the URLconf" in response.content.decode())
Key points
- DEBUG = True turns the debug pages on.
- A debug page shows the error and the lines around it.
- A broken view gives a 500 status.
- A missing page with DEBUG on lists the tried addresses.
In this example, the setup lines configure Django. DEBUG is True, so the debug pages show. The home view returns the home page. The broken view divides by zero. The test client is built with raise_request_exception=False, so the error stays in the response instead of stopping the program. The prints show the 200 status, the 500 status, and the word Traceback in the debug page. The last prints show the 404 status and the tried addresses on the debug page.
Note
Never leave DEBUG on for a live site.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the debug page show for a broken view?