How to Fix Disallowed Host Error in Django Quickly
DisallowedHost error happens when a request comes from a host not listed in ALLOWED_HOSTS in your settings.py. To fix it, add the domain or IP address you expect to receive requests from into the ALLOWED_HOSTS list.Why This Happens
Django protects your app from HTTP Host header attacks by checking if the incoming request's host is in the ALLOWED_HOSTS list. If the host is missing or incorrect, Django raises a DisallowedHost error.
ALLOWED_HOSTS = []
The Fix
Update your ALLOWED_HOSTS in settings.py to include the domain names or IP addresses your app will serve. This tells Django to accept requests from these hosts.
ALLOWED_HOSTS = ['example.com', 'www.example.com', 'localhost', '127.0.0.1']
Prevention
Always set ALLOWED_HOSTS before deploying your Django app to production. Use environment variables or configuration files to manage hosts safely. Avoid using ['*'] in production as it disables this security check.
Test your app locally with localhost and your production domain to ensure hosts are correctly configured.
Related Errors
Other common errors include:
- ImproperlyConfigured: Happens if
ALLOWED_HOSTSis empty in production. - CSRF verification failed: Can occur if host headers don't match expected values.
Fix these by ensuring your host and CSRF settings align with your deployment environment.