Accessing and debugging the Django development server from another machine
Set up development server to listen to external requests
By default, when using the Django management
runserver command, the development server will only listen to requests originating from the local machine (using the loopback address
127.0.0.1). Luckily, the runserver command accepts an IP address and port. Specifying
0.0.0.0 will allow the server to accept requests from any machine:
python manage.py runserver 0.0.0.0:8000
I do not have to worry about security issues with the development server listening to all requests, since the VM is protected from external access by a firewall.
Set up server to send debug information to local network
While the first step will allow us to access the development server from the host machine, we will not be able to see debugging information (for example, the django-debug-toolbar will not be displayed on the host machine, even if
DEBUG is set to True). Django uses another setting,
INTERNAL_IPS, to determine which machines are allowed to view debugging information.
For a typical installation, I set
INTERNAL_IPS to only specify
127.0.0.1, allowing me to easily debug Django apps running on the local machine.
INTERNAL_IPS = ('127.0.0.1',)
Now, since the setting is a tuple, we could easily add the IP address of the host machine and call it a day. We would run into the same problem as the last post, which is the reason I installed Samba in order to access the VM using its host name instead of IP address. Whenever the machine gets a new IP address from the DHCP server, I would have to update the setting. I found a great solution to this problem in this snippet, which adds wildcard support to
INTERNAL_IPS. I personally put this code inside an if block, so that it only executes in a development setting. Here is the code from the end of my settings.py file:
if DEBUG: from fnmatch import fnmatch class glob_list(list): def __contains__(self, key): for elt in self: if fnmatch(key, elt): return True return False INTERNAL_IPS = glob_list(['127.0.0.1', '192.168.*.*'])
Now, I can access and debug Django projects using the development server from any machine on my local network.