When developing a Django application, you may need to:
- Set up a custom hostname (djangosite.local) for local testing on your Windows machine.
- Allow access from other devices on your local network using your local IP address.
This guide explains how to configure Django for both local and LAN testing without exposing your app to the internet.
Step 1: Set Up a Custom Hostname (Windows Only)
To test locally with djangosite.local (only works on your machine):
- Open Notepad as Administrator.
- Edit the hosts file at:
C:\Windows\System32\drivers\etc\hosts
- Add these lines:
127.0.0.1 djangosite.local 127.0.0.1 api.djangosite.local
- Save the file.
Now, you can access Django locally via:
http://djangosite.local:8000
http://api.djangosite.local:8000
Step 2: Allow LAN Access (Other Devices)
Since djangosite.local won't work on other devices, use your local IP instead.
1. Find Your Windows Local IP
- Open Command Prompt and run:
ipconfig
- Look for IPv4 Address (e.g.,
192.168.1.100
).
2. Configure Django for LAN Access
In settings.py, add your local IP to ALLOWED_HOSTS:
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost',
'djangosite.local',
'api.djangosite.local',
'192.168.1.100' # Replace with your actual local IP
]
3. Run Django on All Network Interfaces
python manage.py runserver 0.0.0.0:8000
Now, other devices on your LAN can access your Django app via:
http://[YOUR_LOCAL_IP]:8000 (e.g., http://192.168.1.100:8000)
Important Notes
- 🔒 Security: Never use
ALLOWED_HOSTS = ['*']
in production. - 🌐 Hostname Limitation: djangosite.local only works on your machine. Other devices must use your local IP.
- 🔄 Dynamic IP? If your local IP changes, update ALLOWED_HOSTS accordingly.
Conclusion
- Use djangosite.local for local testing (Windows-only).
- Use your local IP (192.168.x.x) for LAN testing on other devices.
- Always restrict ALLOWED_HOSTS for security.