Skip to content

Commit

Permalink
Rework DEBUG_TOOLBAR_CONFIG
Browse files Browse the repository at this point in the history
... by removing it.

The setting for SHOW_TOOLBAR_CALLBACK seems to have been an attempt
to work around issues when running inside docker. Debug toolbar tries
to handle this case, but it doesn't work sufficiently (at least in my
case). The documentation has an opinion on this matter:

  Do not use
    DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": lambda request: DEBUG}
  in your project’s settings.py file.

This commit is longer than I'd like, but the setting of INTERNAL_IPS
seems to really fix it, and solves the fact that the debug context
processor wasn't working either. With this fixed, {% debug %} works
in templates.

INTERNAL_IPS should best contain IP addresses rather than hostnames.

IS_RUNNING_TESTS... no idea why we would want the toolbar while
running tests.
  • Loading branch information
friedelwolff committed Aug 1, 2024
1 parent 5014e2d commit 08f858b
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions app/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,41 @@
}
}

# toolbar settings
if DEBUG:
DEBUG_TOOLBAR_CONFIG = {
"IS_RUNNING_TESTS": False,
"SHOW_TOOLBAR_CALLBACK": lambda request: DEBUG,
}
# Some things rely on the setting INTERNAL_IPS:
# - debug_toolbar.middleware.show_toolbar
# - django.template.context_processors.debug
# See https://docs.djangoproject.com/en/stable/ref/settings/#internal-ips
# Inside a docker container, it isn't trivial to get the IP address of the
# Docker host that will appear in REMOTE_ADDR. The following seems to work
# for now to add support for a range of IP addresses without having to put
# a huge list in INTERNAL_IPS, e.g. with
# map(str, ipaddress.ip_network('172.0.0.0/24'))
# If this can't resolve the name "host.docker.internal", nothing is added
# to INTERNAL_IPS.
import socket

try:
ip = socket.gethostbyname("host.docker.internal")
except socket.gaierror:
# presumably not in docker
ip = None

import ipaddress

# Based on https://code.djangoproject.com/ticket/3237#comment:12
class CIDRList(list):
def __init__(self, addresses):
"""Create a new ip_network object for each address range provided."""
self.networks = [ipaddress.ip_network(address, strict=False) for address in addresses]

def __contains__(self, address):
"""Check if the given address is contained in any of the networks."""
return any([ipaddress.ip_address(address) in network for network in self.networks])

if ip:
INTERNAL_IPS = CIDRList([f"{ip}/8"])

INTERNAL_IPS = [
"host.docker.internal",
]

# Email settings
EMAIL_HOST = os.environ.get("EMAIL_HOST")
Expand Down

0 comments on commit 08f858b

Please sign in to comment.