Last updated: Apr 13, 2024
Reading time·2 min
The error "ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings" occurs when Django doesn't know which settings you're using.
To solve the error, set the DJANGO_SETTINGS_MODULE
environment variable and
restart your development server.
If you are on macOS or Linux, set the DJANGO_SETTINGS_MODULE
environment
variable as follows.
# On macOS and Linux export DJANGO_SETTINGS_MODULE=mysite.settings
mysite
placeholder with the name of your project.If you are on Windows and use CMD (Command Prompt), use the set
command
instead.
# On Windows, CMD set DJANGO_SETTINGS_MODULE=mysite.settings
If you are on Windows and use PowerShell, use the following command instead.
# On Windows, PowerShell $env:DJANGO_SETTINGS_MODULE="mysite.settings"
mysite
placeholder with the name of your project.If you've deployed your project to Heroku, you would also have to issue the
heroku config:set
command.
heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <YOUR_ACCOUNT_NAME>
As shown in
this section
of the docs, the DJANGO_SETTINGS_MODULE
environment variable informs Django
which settings you're using.
python manage.py shell
commandIf the error persists, issue the python manage.py shell
command.
python manage.py shell # Or python3 python3 manage.py shell # Or with the py alias (Windows) py manage.py shell
When you use the python manage.py shell
command, it tells Django which
settings file to use before starting the interactive interpreter.
python manage.py shell
command, it takes care of setting DJANGO_SETTINGS_MODULE
for you.Make sure your terminal is opened in your project's root directory (right next
to your manage.py
) file before you run the command.
manage.py
fileIf none of the suggestions worked, try to update the contents of your
manage.py
file by adding the following lines at the top.
import os # ⛔️ Make sure to replace `mysite` with your project's name os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'mysite.settings' ) import django django.setup()
mysite
placeholder with the name of your project.Also note that the order in which the lines are added matters.
We first set the DJANGO_SETTINGS_MODULE
environment variable and then import
django
.
You can learn more about the related topics by checking out the following tutorials: