skip to Main Content

I want to deploy my Django app and I already used gunicorn, nginx and supervisor and stored on AWS EC2

Here is the snippet of my settings.py

DEBUG = False

ALLOWED_HOSTS = ['<my_ip>', '<my_ip>.ap-southeast-1.compute.amazonaws.com']

I have settings_prod.py and settings_dev.py

settings_prod.py

DEBUG = False

ALLOWED_HOSTS = [
    '<my_ip>', '<my_ip>.ap-southeast-1.compute.amazonaws.com']

From my wsgi.py

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'votingapp.settings_prod')

I put the correct host address and it still got the same error:

Exception Type: DisallowedHost
Exception Value:    
Invalid HTTP_HOST header: '<ip>'. You may need to add '<ip>' to ALLOWED_HOSTS.

The problem is it uses settings from settings_dev.py which is not my ideal sequence. I want the supervisor or settings_dev.py to allow my IP to host the site.

Any help would be appreciated.

2

Answers


  1. Add your IP in ALLOWED HOSTS

    DEBUG = False
    
    ALLOWED_HOSTS = [
        'your IP',
    ]
    

    Then your can run your server as
    python manage.py runserver yourIP:port

    Login or Signup to reply.
  2. I had the same issue, and I’ve solved it with following steps:

    1. I use .env files with my project (for managing it I use python-decouple package);
    2. I separate all my settings to dev and prod py files with base common python file.
    3. Next, I import all settings from .base, .dev and .prod and manage them with PROJECT env var (if env var set to dev, use dev settings).

    __init__.py file:

    from .base import *
    
    if config("PROJECT") == "prod":
        from .prod import *
    else:
        from .dev import *
    

    config set in base.py:

    from decouple import AutoConfig
    
    PROJECT_ROOT = Path(__file__).resolve().parent.parent
    BASE_DIR = PROJECT_ROOT.parent
    
    ENV_FILE_PATH = BASE_DIR.parent / '.env'
    config = AutoConfig(ENV_FILE_PATH)
    

    structure of settings sub-package in my django project:

    ...
    settings
      ├── __init__.py
      ├── base.py
      ├── dev.py
      └── prod.py
    

    If you use AWS ES2, then you probably already have env vars in your project, so you can just replace python-decouple by your solution (like os.environ as default) and then manage your settings with your custom setted env var.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search