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?
6
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.