Forums

Django site live at username.pythonanywhere.com, but only from some computers

Hi, my Django site at http://username.pythonanywhere.com/ is live, but only accessible from username.pythonanywhere.com If I try accessing it in browser by typing in www.username.pythonanywhere.com I see the default PA message:

Coming Soon! This is going to be another great website hosted by PythonAnywhere page.

I have a basic paid $5 package and my settings.py files has these allowed hosts:

ALLOWED_HOSTS = [
    'username.pythonanywhere.com',
    '.pythonanywhere.com',
    '.googleapis.com',
]

Should it be something like

ALLOWED_HOSTS = [
    'username.pythonanywhere.com',
    'www.username.pythonanywhere.com',
    '.pythonanywhere.com',
    '.googleapis.com',
]

Can someone give me a hand please? I'm new at this. Cheers, Jurgen

Hi Jurgen,

A slightly long answer for you, but I figured it was best to explain things properly rather than just give you the tl;dr version :-) But in case you just want the short version -- we only support web apps on your own custom domains and on yourusername.pythonanywhere.com. www.yourusername.pythonanywhere.com is not supported.

OK, here's the details:

The ALLOWED_HOSTS Django setting just tells it that it's OK if it receives requests for those sites. The only thing you should have in there for a site at jurgenizer.pythonanywhere.com is jurgenizer.pythonanywhere.com. The only way in which it's connected to the host names that are used to access your site is that those host names must appear in it. So, if X is a hostname for your site, it must appear in there, but X being in there doesn't make it a hostname for your site.

Routing requests to your web app is done by a combination of DNS and the web apps you have set up on the "Web" tab. If you had a domain www.something.com registered with a domain name registrar, you'd set up a web app on the "Web" tab called "www.something.com". This would give you an identifier of a part of PythonAnywhere (something like webapp-1234.pythonanywhere.com), and you'd then go to your registrar and set up some DNS settings to say that www.something.com has a "CNAME" pointing that address to webapp-1234.pythonanywhere.com. So requests to www.something.com would go to the appropriate part of PythonAnywhere, which would recognise them as belonging to a particular web app, and process them using the code for that web app.

Of course, in this case, you don't own the pythonanywhere.com domain, so all of the DNS stuff has already been done by us. Basically we've set it up so that yourusername`.pythonanywhere.com always goes to the appropriate part of PythonAnywhere for that user's web apps.

But we haven't done the equivalent DNS setup for www.yourusername.pythonanywhere.com.

Does that make things a bit clearer?

That is excellent answer, I have a much better understanding of how it works - thank you for the fast response too!

No problem, glad to help!

Excuse me for my question) but this means that I need to specify allowed hosts www.mydomain.com? not a cname?

You need to specify the address that you web app is served from i.e. the name at the top of the web app configuration page.

Thank you so much, bro! The problem as always was that the domain was not yet registered

I am tired of this error

DisallowedHost at / Invalid HTTP_HOST header: 'subrahmanyam0326.pythonanywhere.com'. You may need to add 'subrahmanyam0326.pythonanywhere.com' to ALLOWED_HOSTS.

settings.py:

ALLOWED_HOSTS=['subrahmanyam0326.pythonanywhere.com']

Can we take a look at your code? We can see it from our admin interface, but we always ask for permission first.

I still cannot make it work... This is my settings.py:

from dotenv import load_dotenv
from pathlib import Path
import logging
import os
import sys

load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

SECRET_KEY = os.getenv("SECRET_KEY")

Logger = logging.getLogger(__name__)
Logger.error(Path.cwd())

IS_PRODUCTION = os.getenv('DJANGO_PRODUCTION', 'False') == 'True'

if IS_PRODUCTION:
    DEBUG = False
    ALLOWED_HOSTS = ['sirjude.pythonanywhere.com']

    # # Security settings for production
    # SECURE_HSTS_SECONDS = 31536000  # 1 year
    # SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    # SECURE_HSTS_PRELOAD = True
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
else:
    DEBUG = True
    ALLOWED_HOSTS = ['localhost', '127.0.0.1']
...

<br>

This is my .env file inside the same folder where is settings.py:

SECRET_KEY=<my django secret key>
DJANGO_PRODUCTION=False
DB_ENGINE=django.db.backends.postgresql
DB_NAME=app
DB_USER=super
DB_PASSWORD=<my postgrespassword>
DB_HOST=SirJude-4090.postgres.pythonanywhere-services.com
DB_PORT=14090

<br>

...but I keep receiving this error:

2024-10-08 12:18:46,401: Invalid HTTP_HOST header: 'sirjude.pythonanywhere.com'. You may need to add 'sirjude.pythonanywhere.com' to ALLOWED_HOSTS.
Traceback (most recent call last):
  File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/utils/deprecation.py", line 133, in __call__
    response = self.process_request(request)
  File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/middleware/common.py", line 48, in process_request
    host = request.get_host()
  File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/http/request.py", line 151, in get_host
    raise DisallowedHost(msg)
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'sirjude.pythonanywhere.com'. You may need to add 'sirjude.pythonanywhere.com' to ALLOWED_HOSTS.
2024-10-08 12:18:46,582: Error running WSGI application
2024-10-08 12:18:46,582: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
2024-10-08 12:18:46,582:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 124, in __call__
2024-10-08 12:18:46,583:     response = self.get_response(request)
2024-10-08 12:18:46,583: 
2024-10-08 12:18:46,583:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 140, in get_response
2024-10-08 12:18:46,583:     response = self._middleware_chain(request)
2024-10-08 12:18:46,583: 
2024-10-08 12:18:46,583:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner
2024-10-08 12:18:46,583:     response = response_for_exception(request, exc)
2024-10-08 12:18:46,583: 
2024-10-08 12:18:46,584:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 140, in response_for_exception
2024-10-08 12:18:46,584:     response = handle_uncaught_exception(
2024-10-08 12:18:46,584: 
2024-10-08 12:18:46,584:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 181, in handle_uncaught_exception
2024-10-08 12:18:46,584:     return debug.technical_500_response(request, *exc_info)
2024-10-08 12:18:46,584: 
2024-10-08 12:18:46,584:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/views/debug.py", line 69, in technical_500_response
2024-10-08 12:18:46,584:     html = reporter.get_traceback_html()
2024-10-08 12:18:46,584: 
2024-10-08 12:18:46,585:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/views/debug.py", line 428, in get_traceback_html
2024-10-08 12:18:46,585:     c = Context(self.get_traceback_data(), use_l10n=False)
2024-10-08 12:18:46,585: 
2024-10-08 12:18:46,585:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/views/debug.py", line 397, in get_traceback_data
2024-10-08 12:18:46,585:     "settings": self.filter.get_safe_settings(),
2024-10-08 12:18:46,585: 
2024-10-08 12:18:46,585:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/views/debug.py", line 156, in get_safe_settings
2024-10-08 12:18:46,586:     settings_dict[k] = self.cleanse_setting(k, getattr(settings, k))
2024-10-08 12:18:46,586: 
2024-10-08 12:18:46,586:   File "/home/SirJude/Blog/.venv/lib/python3.10/site-packages/django/conf/__init__.py", line 98, in __getattr__
2024-10-08 12:18:46,586:     raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

Any help, please!!!

See https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/

Thank you, Glenn. I had already tried that, but it still does not work...

I have:
- created a .env file inside Blog/app/
- deleted the previous .venv folder and created one with "mkvirtualenv venv"
- launched workon venv
- installed all the libraries in the requirements.txt
- moved venv inside .virtualenvs with mv venv ~/.virtualenvs/venv
- tested echo $SECRET_KEY (it works)

This is the wsgi.py file:

import os  
import sys  
from dotenv import load_dotenv  
from django.core.wsgi import get_wsgi_application

# Adjust this path to your project directory
path = '/home/SirJude/Blog'
if path not in sys.path:
    sys.path.insert(0, path)

# Path to the folder containing the .env file
env_folder = os.path.expanduser('/home/SirJude/Blog/app')
# Load environment variables from the .env file
load_dotenv(os.path.join(env_folder, '.env'))

# Set the default Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

# Get the WSGI application
application = get_wsgi_application()
  • I launched the command:
    echo 'set -a; source /home/SirJude/Blog/app/.env; set +a' >> ~/.virtualenvs/venv/bin/postactivate

Finally: - I corrected the path to the virtual environment in the tab web:

Virtualenv:
Use a virtualenv to get different versions of flask, django etc from our default system ones. More info here. You need to Reload your web app to activate it; NB - will do nothing if the virtualenv does not exist.

/home/SirJude/.virtualenvs/venv

  • I reloded the application.

...but I still get the same message:

2024-10-08 18:16:59,817: Invalid HTTP_HOST header: 'sirjude.pythonanywhere.com'. You may need to add 'sirjude.pythonanywhere.com' to ALLOWED_HOSTS.
Traceback (most recent call last):
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/utils/deprecation.py", line 133, in __call__
    response = self.process_request(request)
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/middleware/common.py", line 48, in process_request
    host = request.get_host()
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/http/request.py", line 151, in get_host
    raise DisallowedHost(msg)
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'sirjude.pythonanywhere.com'. You may need to add 'sirjude.pythonanywhere.com' to ALLOWED_HOSTS.
2024-10-08 18:16:59,971: Error running WSGI application
2024-10-08 18:16:59,971: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
2024-10-08 18:16:59,972:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 124, in __call__
2024-10-08 18:16:59,972:     response = self.get_response(request)
2024-10-08 18:16:59,972: 
2024-10-08 18:16:59,972:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 140, in get_response
2024-10-08 18:16:59,972:     response = self._middleware_chain(request)
2024-10-08 18:16:59,972: 
2024-10-08 18:16:59,972:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner
2024-10-08 18:16:59,972:     response = response_for_exception(request, exc)
2024-10-08 18:16:59,973: 
2024-10-08 18:16:59,973:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 140, in response_for_exception
2024-10-08 18:16:59,973:     response = handle_uncaught_exception(
2024-10-08 18:16:59,973: 
2024-10-08 18:16:59,973:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 181, in handle_uncaught_exception
2024-10-08 18:16:59,973:     return debug.technical_500_response(request, *exc_info)
2024-10-08 18:16:59,974: 
2024-10-08 18:16:59,974:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/views/debug.py", line 69, in technical_500_response
2024-10-08 18:16:59,974:     html = reporter.get_traceback_html()
2024-10-08 18:16:59,974: 
2024-10-08 18:16:59,974:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/views/debug.py", line 428, in get_traceback_html
2024-10-08 18:16:59,974:     c = Context(self.get_traceback_data(), use_l10n=False)
2024-10-08 18:16:59,974: 
2024-10-08 18:16:59,974:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/views/debug.py", line 397, in get_traceback_data
2024-10-08 18:16:59,975:     "settings": self.filter.get_safe_settings(),
2024-10-08 18:16:59,975: 
2024-10-08 18:16:59,975:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/views/debug.py", line 156, in get_safe_settings
2024-10-08 18:16:59,975:     settings_dict[k] = self.cleanse_setting(k, getattr(settings, k))
2024-10-08 18:16:59,975: 
2024-10-08 18:16:59,975:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 98, in __getattr__
2024-10-08 18:16:59,975:     raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

What is the value of IS_PRODUCTION when you expect to be True?

It is in the .env file:
<br>

SECRET_KEY=<my django secret key>
DJANGO_PRODUCTION=False
DB_ENGINE=django.db.backends.postgresql
DB_NAME=app
DB_USER=super
DB_PASSWORD=<my postgrespassword>
DB_HOST=SirJude-4090.postgres.pythonanywhere-services.com
DB_PORT=14090

It is set to "False" for debugging, but in the settings.py there is this line:

IS_PRODUCTION = os.getenv('DJANGO_PRODUCTION', 'False') == 'True'

I have also already tried to set directly to True and change the line in the settings.py as:

IS_PRODUCTION = os.getenv('DJANGO_PRODUCTION')

It still does not work...

Could you (inside your runnig web app) print/log repr of values of all the env vars that you expect to be set? (you can skip secrets)

I modified the settings.py in this way:

from dotenv import load_dotenv
from pathlib import Path
import logging
import os
import sys

load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

SECRET_KEY = os.getenv("SECRET_KEY")

Logger = logging.getLogger(__name__)
Logger.error(Path.cwd())

IS_PRODUCTION = os.getenv('DJANGO_PRODUCTION', 'False') == 'True'


if IS_PRODUCTION:
    DEBUG = False
    ALLOWED_HOSTS = ['sirjude.pythonanywhere.com']

    env_vars_to_log = [
    "DJANGO_PRODUCTION",  # This one defines production or dev mode
    "DB_ENGINE",  # Database engine
    "DB_NAME",  # Database name
    "DB_USER",  # Database user
    "DB_HOST",  # Database host
    "DB_PORT",  # Database port
    ]

    for var in env_vars_to_log:
        Logger.error(f"{var}: {repr(os.getenv(var))}")

    # # Security settings for production
    # SECURE_HSTS_SECONDS = 31536000  # 1 year
    # SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    # SECURE_HSTS_PRELOAD = True
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
else:
    DEBUG = True
    ALLOWED_HOSTS = ['localhost', '127.0.0.1']
...

Then I clicked on run in the top-right corner and the result in the console was:

/home/SirJude/Blog/app
DJANGO_PRODUCTION: 'True'
DB_ENGINE: 'django.db.backends.postgresql'
DB_NAME: 'app'
DB_USER: 'super'
DB_HOST: 'SirJude-4090.postgres.pythonanywhere-services.com'
DB_PORT: '14090'

Then in the web tab, I reloded the app, but I got again the same error:

2024-10-09 12:07:46,664: Invalid HTTP_HOST header: 'sirjude.pythonanywhere.com'. You may need to add 'sirjude.pythonanywhere.com' to ALLOWED_HOSTS.
Traceback (most recent call last):
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/utils/deprecation.py", line 133, in __call__
    response = self.process_request(request)
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/middleware/common.py", line 48, in process_request
    host = request.get_host()
  File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/http/request.py", line 151, in get_host
    raise DisallowedHost(msg)
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'sirjude.pythonanywhere.com'. You may need to add 'sirjude.pythonanywhere.com' to ALLOWED_HOSTS.
2024-10-09 12:07:46,964: Error running WSGI application
2024-10-09 12:07:46,965: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
2024-10-09 12:07:46,965:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 124, in __call__
2024-10-09 12:07:46,965:     response = self.get_response(request)
2024-10-09 12:07:46,965: 
2024-10-09 12:07:46,965:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 140, in get_response
2024-10-09 12:07:46,965:     response = self._middleware_chain(request)
2024-10-09 12:07:46,965: 
2024-10-09 12:07:46,965:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner
2024-10-09 12:07:46,966:     response = response_for_exception(request, exc)
2024-10-09 12:07:46,966: 
2024-10-09 12:07:46,966:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 140, in response_for_exception
2024-10-09 12:07:46,966:     response = handle_uncaught_exception(
2024-10-09 12:07:46,966: 
2024-10-09 12:07:46,966:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 181, in handle_uncaught_exception
2024-10-09 12:07:46,966:     return debug.technical_500_response(request, *exc_info)
2024-10-09 12:07:46,966: 
2024-10-09 12:07:46,966:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/views/debug.py", line 69, in technical_500_response
2024-10-09 12:07:46,967:     html = reporter.get_traceback_html()
2024-10-09 12:07:46,967: 
2024-10-09 12:07:46,967:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/views/debug.py", line 428, in get_traceback_html
2024-10-09 12:07:46,967:     c = Context(self.get_traceback_data(), use_l10n=False)
2024-10-09 12:07:46,967: 
2024-10-09 12:07:46,967:   File "/home/SirJude/.virtualenvs/venv/lib/python3.10/site-packages/django/views/debug.py", line 397, in get_traceback_data

If you are still getting that error with that code, then the most likely cause is that you are not loading your dotenv file or that it does not contain the DJANGO_PRODUCTION variable. See https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/