Skip to content

Instantly share code, notes, and snippets.

@eezis
Last active June 28, 2023 16:23
Show Gist options
  • Save eezis/7586964 to your computer and use it in GitHub Desktop.
Save eezis/7586964 to your computer and use it in GitHub Desktop.
Resolving Bad Request (400) when using Django on an EC2 instance DEBUG
This gist pertains to a Bad Request(400) error when trying to access an EC2 instance running django . . .
I set up an EC2 server, installed django, started runserver and tested. The result was
Bad Request (400)
When using Django 1.5 and higher, if you specify DEBUG=False in the settings.py file, you must also specify ALLOWED_HOSTS
or you will recieve a "Bad Request (400)" error message when attempting to retrieve a page.
On an Amazone EC2 instance, if you are ***testing*** with the public DNS, then you should include the public DNS as one of the allowed hosts.
--- example ---
DEBUG = False
ALLOWED_HOSTS = ['.yourdomain.com', 'ec2-XX-XX-XX-XXX.us-west-2.compute.amazonaws.com',]
--- end ---
If have SSH'ed into the server and wish to perform on-server testing you should include 'localhost' as well:
python manage.py runserver 0:8000
then . . .
curl http://localhost:8000/
or . . .
telnet localhost 8000 (then type GET / and hit enter twice)
If that does not work add 'localhost' to your ALLOWED_HOSTS file.
ALLOWED_HOSTS = ['.yourdomain.com', 'ec2-XX-XX-XX-XXX.us-west-2.compute.amazonaws.com', 'localhost',]
========
NOTE WELL: If you reboot your EC2 instance, when it reboots it will have a different public DNS and you
will need to update your ALLOWED_HOSTS accordingly.
See the 1.5 release notes for more:
https://docs.djangoproject.com/en/dev/releases/1.5/#allowed-hosts-required-in-production
@jhagege
Copy link

jhagege commented Jul 8, 2015

+1

@shihweilo
Copy link

I too had this issue and solved it by adding following to wsgi.py

import sys, os
sys.path.insert(0, '/opt/python/current/app')   # I use ElasticBeanstalk, modify to your project path
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your.settings')

@attolee
Copy link

attolee commented Jun 24, 2016

I got 400 error, because I forget to import a model class in views.

@gautamyadavs
Copy link

+1

@brunnooliver7
Copy link

+1

@engmsilva
Copy link

+1

@la5chine
Copy link

+1

@mahes1287
Copy link

+1

@yalattas
Copy link

+1

@mlmr
Copy link

mlmr commented Feb 8, 2023

+1

@iamrahulrnair
Copy link

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment