Setup django-debug-toolbar in a dockerized app
To install and set up django-debug-toolbar
you can follow the instruction from the official documentation .
Works fine for "classic" application setup locally but if you use Docker to spin up your project locally, you will find out that it does not work.
There are more configuration to add in order to make it play nice with Docker.
The Django Debug Toolbar checks the IP address of incoming requests to determine if it should show the toolbar. By default, it only allows requests from 127.0.0.1
.
When running your app in Docker, your requests might originate from a different internal IP address. You can allow these requests by modifying INTERNAL_IPS
in your settings.py
# settings.py
# DEBUG_TOOLBAR
INTERNAL_IPS = [
"127.0.0.1",
]
# Include Docker's default internal IP range (e.g., 172.16.0.0/12)
docker_host_ip = os.environ.get("DOCKER_HOST_IP", "172.17.0.1")
INTERNAL_IPS.append(docker_host_ip)
DEBUG_TOOLBAR_CONFIG = {
# Always show toolbar if debug is true
"SHOW_TOOLBAR_CALLBACK": lambda request: True,
# Disable redirect interception for better performance
"INTERCEPT_REDIRECTS": False,
}
And if you are using HTMX, don't forget to add the script bellow in your base template:
{% if debug %}
<script>
if (typeof window.htmx !== "undefined") {
htmx.on("htmx:afterSettle", function (detail) {
if (
typeof window.djdt !== "undefined"
&& detail.target instanceof HTMLBodyElement
) {
djdt.show_toolbar();
}
});
}
</script>
{% endif %}