Debugging Django Applications - Django Debug Toolbar
In my previous post I showed you how to setup VSCode in order to debug Django applications. In this post, I will show you how to the Django Debug Toolbar and how to install it.
The Django debug toolbar is a powerful tool that you can use in your Django apps during development, to help you debug your applications. The debug toolbar essentially it helps you see a tonne of information that Django uses to generate the pages.
To get started, the first thing you have to do in pip install the toolbar:
$ python -m pip install django-debug-toolbar
The next step is to add the debug toolbar in the list of apps in your settings module:
INSTALLED_APPS = [
# ...
'django.contrib.staticfiles',
# ...
'debug_toolbar',
]
STATIC_URL = '/static/'
The next step is to add the Debug Toolbar’s URLs to your project’s URLconf, don't forget to also import debug_toolbar
at the top of your urls.py file!
import debug_toolbar
from django.conf import settings
from django.urls import include, path
urlpatterns = [
...
path('__debug__/', include(debug_toolbar.urls)),
]
Then you need to enable the debug toolbar middleware. We use middleware to hook into Django's request / response processing. The Debug Toolbar is mostly implemented in a middleware. Enable it in your settings module as follows:
MIDDLEWARE = [
# ...
'debug_toolbar.middleware.DebugToolbarMiddleware',
# ...
]
Warning The order of MIDDLEWARE is important. You should include the Debug Toolbar middleware as early as possible in the list. However, it must come after any other middleware that encodes the response’s content, such as GZipMiddleware
.
The final step is to configure the internal IPs settings. For your local development you should add the IP address 127.0.0.1
for your local IPs settings. By default, INTERNAL_IPS
is not present in the Django settings file when you create a new Django project, so you need to add this yourself:
INTERNAL_IPS = [
# ...
'127.0.0.1',
# ...
]
Now you have completed all the steps!
Note The debug toolbar in Django only works if your Django templates are serving proper HTML documents!