[Django]-Django ALLOWED_HOSTS: OK to include 'localhost' on a deployed settings file?

15👍

As long as the app does not give superpowers to requests with ‘localhost’ in the Host http header it should be ok.

6👍

In Django 2.1.4, another solution is:
ALLOWED_HOSTS = ['127.0.0.1']

0👍

This is the way I have done. Like this I can change between localhost and production.

ALLOWED_HOSTS = ['127.0.0.1', 'your_deployed_host_url' ]

#and set your db to work on both db::

if 'DATABASE_URL' in os.environ:
    DATABASES = {
        'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))
    }
else:
    print("Postgres URL not found, using sqlite instead")
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

0👍

Method 1:

To quickly create a custom error page for the 404 error, place a file named 404.html in your root template directory. For other errors like 400, 500, and 403, follow the same pattern by creating 400.html, 500.html, and 403.html respectively in the same root template directory.

Source: Django documentation on serving static files

Method 2:

To customize error pages in Django, follow these steps:

  1. Open your Django root urls.py file.

  2. Add the following lines to associate specific views with different error codes:

    from django.conf.urls import (handler400, handler403, handler404, handler500)
    
    handler400 = 'app.views.bad_request'
    handler403 = 'app.views.permission_denied'
    handler404 = 'app.views.page_not_found'
    handler500 = 'app.views.server_error'
    

    Replace 'app.views.bad_request', 'app.views.permission_denied', 'app.views.page_not_found', and 'app.views.server_error' with the actual paths to your custom view functions for handling each error.

Source: Django documentation on customizing error views

Keep in mind that if the DEBUG setting in your configuration is set to True, the custom 404 page you create might not be displayed. Instead, Django will show the URL configuration along with debugging information.

0👍

I agree with Peter Tillemans, but if you wanted to be sure you could do something like…

settings.py

import sys

RUNNING_DEVSERVER = len(sys.argv) > 1 and (
    sys.argv[1] == "runserver" or sys.argv[1] == "runserver_plus"
)

ALLOWED_HOSTS = [".mydomain.com"]
if RUNNING_DEVSERVER:
    ALLOWED_HOSTS += ["localhost", "127.0.0.1"]

Leave a comment