Adding dynamic dns hostnames to Django INTERNAL_IPS

While some of us are blessed with fixed IP addresses, some ISPs don’t offer this option unfortunately. If you’re using the Django INTERNAL_IPS setting to show or hide the debug toolbar this can be a problem.

Luckily the Django settings.py files are pure Python and it’s easy enough to work around this issue with a few lines of code:

[python]
import sys

INTERNAL_IPS = [
# Any fixed internal IPs
]

INTERNAL_HOSTS = [
# Some dyndns host
# Some no-ip host
# etc…

# For example:
‘wol.ph’,
]

# Only enable when running through the runserver command
if ‘runserver’ in sys.argv:
import dns.resolver

resolver = dns.resolver.Resolver()
# Set the timeout to 1 so we don’t wait too long
resolver.timeout = 1
resolver.lifetime = 1

for host in INTERNAL_HOSTS:
try:
# For ipv6 you can use AAAA instead of A here
ip = resolver.query(host, ‘A’)[0].address
INTERNAL_IPS.append(ip)
except dns.exception.Timeout:
print(‘Unable to resolve %r, skipping’ % host)
[/python]

Note that the code above uses dnspython which can be installed through pip.

Bookmark and Share

Tags:

About Rick van Hattem

Rick van Hattem is a Dutch Internet entrepreneur and co-founder of Fashiolista.com

3 Responses to “Adding dynamic dns hostnames to Django INTERNAL_IPS”

  1. Geoffrey Callaghan | 2019-04-05 at 00:33:10 #

    you can also use [spam] if you need a static IP

    • Rick van Hattem | 2019-04-05 at 00:46:15 #

      Not sure if you don’t know what you’re talking about or if you’re simply spamming but that’s not a static IP.

      That’s still a dynamic hostname, not a static IP address.

  2. Deyaa | 2022-06-07 at 04:21:22 #

    Cool I wish they had it built-in.

Leave a Reply