Django on PythonAnywhere: ImproperlyConfigured: The SECRET_KEY setting must not be empty
I’m hosting a Django project on PythonAnywhere and encountering the following error when running makemigrations: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
My Setup:
Hosting Platform: PythonAnywhere
Environment Management: Using a .env file to manage secrets
Python Version: 3.10
Django Version: 5.1.2
In my WSGI file, I’ve included the following code to load the .env file:
import sys
from dotenv import load_dotenv
path = '/home/verbsmerch/verbs_backend'
project_folder = os.path.expanduser(path)
load_dotenv(os.path.join(project_folder, '.env'))
In my settings I load the SECRET_KEY like this:
SECRET_KEY = os.getenv("SECRET_KEY")
What I’ve Tried:
- Verified that the .env file exists and is located in the correct directory.
- Checked that the .env file has the correct permissions (chmod 600).
- Ran a Python shell to debug:
from dotenv import load_dotenv
import os
load_dotenv('/home/verbsmerch/verbs_backend/.env')
print(os.getenv("SECRET_KEY")) # This prints the correct key
- Reloaded the web app from the PythonAnywhere Web tab.
Why is Django unable to load the SECRET_KEY when it seems to work in the Python shell? How can I resolve this error?
Not sure where your specific error is coming from but I have hosted web apps on Pythonanywhere and I used python-decouple to manage my .env files. Please see How to Use Python Decouple to set up and configure your environment variables.
The Django settings
module contains all the configuration of your Django installation. As a corollary, it is loaded first and all "settings" are applied before the WSGI server is spun.
In your case, SECRET_KEY = os.getenv("SECRET_KEY")
runs first before load_dotenv(os.path.join(project_folder, '.env'))
because the former is contained within the settings
module whereas the latter is contained within the wsgi
module.
You have to reconsider the set location of load_dotenv(os.path.join(project_folder, '.env'))
to finally get it right. I would suggest loading the environment variables from within the settings
module then using them right away in the settings
module and anywhere else after.