131👍
I had the same error and it turned out to be a circular dependency between a module or class loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.
94👍
I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield’s book Two scoops of Django.
I resolved the issue by setting
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local")
in manage.py
and wsgi.py
.
Update:
In the above solution, local
is the file name (settings/local.py) inside my settings folder, which holds the settings for my local environment.
Another way to resolve this issue is to keep all your common settings inside settings/base.py and then create 3 separate settings files for your production, staging and dev environments.
Your settings folder will look like:
settings/
__init__.py
base.py
local.py
prod.py
stage.py
and keep the following code in your settings/__init__.py
from .base import *
env_name = os.getenv('ENV_NAME', 'local')
if env_name == 'prod':
from .prod import *
elif env_name == 'stage':
from .stage import *
else:
from .local import *
- [Django]-How to concatenate strings in django templates?
- [Django]-Django :How to integrate Django Rest framework in an existing application?
- [Django]-Why is __init__ module in django project loaded twice
23👍
I had the same error with python manage.py runserver
.
For me, it turned out that it was because of a stale compiled binary (.pyc) file. After deleting all such files in my project, server started running again. 🙂
So if you get this error, out of nowhere, i.e without making any change seemingly-related to django-settings, this could be a good first measure.
- [Django]-Django admin default filter
- [Django]-Django: guidelines for speeding up template rendering performance
- [Django]-How to save pillow image object to Django ImageField?
18👍
Remove .pyc files
Ubuntu terminal command for deleting .pyc :
find . -name "*.pyc" -exec rm -rf {} \;
I have got same error when I did python manage.py runserver. It was because .pyc file. I deleted .pyc file from project directory then it was working.
- [Django]-How can I check the size of a collection within a Django template?
- [Django]-Select between two dates with Django
- [Django]-Django: Redirect to previous page after login
16👍
I hadn’t specified the settings file:
python manage.py runserver --settings=my_project.settings.develop
- [Django]-How to use refresh token to obtain new access token on django-oauth-toolkit?
- [Django]-Django: sqlite for dev, mysql for prod?
- [Django]-How to do SELECT MAX in Django?
8👍
It starts working because on the base.py you have all information needed in a basic settings file. You need the line:
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&022shmi1jcgihb*'
So it works and when you do from base import *
, it imports SECRET_KEY into your development.py
.
You should always import basic settings before doing any custom settings.
EDIT:
Also, when django imports development from your package, it initializes all variables inside base since you defined from base import *
inside __init__.py
- [Django]-What is a NoReverseMatch error, and how do I fix it?
- [Django]-Django storages: Import Error – no module named storages
- [Django]-Update all models at once in Django
8👍
I had the same problem with Celery. My setting.py before:
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
after:
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)
If the environment variables are not defined then: SECRET_KEY = YOUR developing key
- [Django]-Django Rest JWT login using username or email?
- [Django]-What's the difference between CharField and TextField in Django?
- [Django]-Can a dictionary be passed to django models on create?
7👍
I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'
- [Django]-How to create an object for a Django model with a many to many field?
- [Django]-Django: Redirect to previous page after login
- [Django]-"gettext()" vs "gettext_lazy()" in Django
- [Django]-Best practices for getting the most testing coverage with Django/Python?
- [Django]-Select distinct values from a table field
- [Django]-Reference list item by index within Django template?
5👍
For anyone using PyCharm: the green “Run selected configuration” button would produce this error, yet running the following works:
py manage.py runserver 127.0.0.1:8000 --settings=app_name.settings.development
To fix this you need to edit the configuration’s environment variables. To do this click the “Select run/debug configuration” drop-down menu to the left of the green run button and then click on “edit configuration”. Under the “environment” tab change the environment variable DJANGO_SETTINGS_MODULE
to app_name.settings.development
.
- [Django]-How to run own daemon processes with Django?
- [Django]-Querying django migrations table
- [Django]-Django: how to do calculation inside the template html page?
4👍
In the init.py of the settings directory write the correct import, like:
from Project.settings.base import *
No need to change wsgi.py or manage.py
- [Django]-How can I list urlpatterns (endpoints) on Django?
- [Django]-Django Rest Framework – Authentication credentials were not provided
- [Django]-Django: how save bytes object to models.FileField?
3👍
I solved this problem occurring on OS X with Django both 1.5 and 1.6 by deactivating all active sessions to virtualenv and starting it again.
- [Django]-How to use regex in django query
- [Django]-On Heroku, is there danger in a Django syncdb / South migrate after the instance has already restarted with changed model code?
- [Django]-Django get the static files URL in view
2👍
To throw another potential solution into the mix, I had a settings
folder as well as a settings.py
in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)
Python was getting confused about whether I wanted to import project/settings.py
or project/settings/__init__.py
. I removed the settings
dir and everything now works fine.
- [Django]-Django models: mutual references between two classes and impossibility to use forward declaration in python
- [Django]-Django queryset filter – Q() | VS __in
- [Django]-Django using get_user_model vs settings.AUTH_USER_MODEL
1👍
I just wanted to add that I got this error when my database name was spelled wrong in my settings.py
file so the DB couldn’t be created.
- [Django]-Django TextField and CharField is stripping spaces and blank lines
- [Django]-Best practices for getting the most testing coverage with Django/Python?
- [Django]-Django.db.utils.ProgrammingError: relation "bot_trade" does not exist
1👍
I solved this problem on 1.8.4 by fixing the TEMPLATES settings which had a typo (removing TEMPLATES[‘debug’] solved it)
Go over the settings that you have changed recently, make sure all keys are by-the-book.
- [Django]-Disable session creation in Django
- [Django]-Django – {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
1👍
My Mac OS didn’t like that it didn’t find the env variable set in the settings file:
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')
but after adding the env var to my local Mac OS dev environment, the error disappeared:
export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'
In my case, I also needed to add the --settings
param:
python3 manage.py check --deploy --settings myappname.settings.production
where production.py is a file containing production specific settings inside a settings folder.
- [Django]-PyCharm: DJANGO_SETTINGS_MODULE is undefined
- [Django]-Change a Django form field to a hidden field
- [Django]-Django models: mutual references between two classes and impossibility to use forward declaration in python
1👍
The issue for me was calling get_text_noop
in the LANGUAGES iterable.
Changing
LANGUAGES = (
('en-gb', get_text_noop('British English')),
('fr', get_text_noop('French')),
)
to
from django.utils.translation import gettext_lazy as _
LANGUAGES = (
('en-gb', _('British English')),
('fr', _('French')),
)
in the base settings file resolved the ImproperlyConfigured: The SECRET_KEY setting must not be empty
exception.
- [Django]-Django: Get model from string?
- [Django]-Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
- [Django]-Invalid http_host header
1👍
The reason why there are so many different answers is because the exception probably doesn’t have anything to do with the SECRET_KEY.
It is probably an earlier exception that is being swallowed.
Turn on debugging using DEBUG=True to see the real exception.
- [Django]-How to put comments in Django templates?
- [Django]-How to force application version on AWS Elastic Beanstalk
- [Django]-How to test auto_now_add in django
1👍
In my case, it was because I was trying to setup django-environ
and I missed an important step:
Note: In the instructions below .env.example and .env should be saved in the same folder as settings.py
I incorrectly assumed that .env
belonged in the root of my project. Moving it to the same folder as settings.py
fixed the problem.
This error message in the Python console was the clue that set me on the right path:
Warning: /Users/allen/PycharmProjects/myapp/myapp/.env doesn't exist - if you're not configuring your environment separately, create one.
- [Django]-Django admin and MongoDB, possible at all?
- [Django]-Django JSONField inside ArrayField
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-Homepage login form Django
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
- [Django]-Django-rest-framework returning 403 response on POST, PUT, DELETE despite AllowAny permissions
0👍
In my case the problem was – I had my app_folder
and settings.py
in it. Then I decided to make Settings folder
inside app_folder
– and that made a collision with settings.py
. Just renamed that Settings folder
– and everything worked.
- [Django]-Django + Ajax
- [Django]-How to access Enum types in Django templates
- [Django]-Django values_list vs values
0👍
I solved the above problem by commenting the line in my settings.py
SECRET_KEY=os.environ.get('SECRET_KEY')
SECRET_KEY
declared in my ~/.bashrc
file(for linux Ubuntu users)
For development purpose on my localmachine I did not use evironmnet variable
SECRET_KEY = '(i9b4aes#h1)m3h_8jh^duxrdh$4pu8-q5vkba2yf$ptd1lev_'
above line didn’t give the error
- [Django]-Django: Arbitrary number of unnamed urls.py parameters
- [Django]-How can I disable logging while running unit tests in Python Django?
- [Django]-Check if celery beat is up and running
0👍
In my case, while setting up a Github action I just forgot to add the env variables to the yml file:
jobs:
build:
env:
VAR1: 1
VAR2: 5
- [Django]-Backwards migration with Django South
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
- [Django]-How to change the name of a Django app?
0👍
In my case, after a long search I found that PyCharm in your Django settings (Settings > Languages & Frameworks > Django) had the configuration file field undefined. You should make this field point to your project’s settings file. Then, you must open the Run / Debug settings and remove the environment variable DJANGO_SETTINGS_MODULE = existing path.
This happens because the Django plugin in PyCharm forces the configuration of the framework. So there is no point in configuring any os.environ.setdefault(‘DJANGO_SETTINGS_MODULE’, ‘myapp.settings’)
- [Django]-AccessDenied when calling the CreateMultipartUpload operation in Django using django-storages and boto3
- [Django]-Disable session creation in Django
- [Django]-How do I get the class of a object within a Django template?
0👍
Import base.py in
__init__.py
alone. make sure you won’t repeat the same configuration again!.set environment variable
SET DJANGO_DEVELOPMENT =dev
settings/
__init__.py
base.py
local.py
production.py
In
__init__.py
from .base import *
if os.environ.get('DJANGO_DEVELOPMENT')=='prod':
from .production import *
else:
from .local import *
In
base.py
configured the global configurations. except for Database. like
SECRET_KEY, ALLOWED_HOSTS,INSTALLED_APPS,MIDDLEWARE .. etc....
In
local.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'database',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}
- [Django]-Change a Django form field to a hidden field
- [Django]-How to force Django models to be released from memory
- [Django]-Django admin: how to sort by one of the custom list_display fields that has no database field
0👍
I came here looking for answer as I was facing the same issues, none of the answers here worked for me. Then after searching in other websites i stumbled upon this simple fix. It worked for me
wsgi.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings')
to
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings.dev')
- [Django]-How to dynamically compose an OR query filter in Django?
- [Django]-How can I change the default Django date template format?
- [Django]-Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found
0👍
Let me share m interesting solution!
I put the
SECRET_KEY = "***&^%$#" in settings packages init.py file and the error disappeared! it’s actually a loading problem!
Hope this quick workaround is useful for some of you!
- [Django]-Django testing: Test the initial value of a form field
- [Django]-Can I access constants in settings.py from templates in Django?
- [Django]-Disable session creation in Django
0👍
try import django then run django.setup() after the secret_key definition. like so:
SECRET_KEY = 'it5bs))q6toz-1gwf(+j+f9@rd8%_-0nx)p-2!egr*y1o51=45XXCV'
django.setup()
- [Django]-Automatic creation date for Django model form objects
- [Django]-In Django, how do I check if a user is in a certain group?
- [Django]-Django Rest Framework File Upload
0👍
For anyone using Wing IDE: set the DJANGO_SETTINGS_MODULE in your project properties to DJANGO_SETTINGS_MODULE=${DJANGO_SITENAME}.config.settings.development
You will find the settings under: Project –> Project Properties and set the value in the field Environment
- [Django]-Embedding JSON objects in script tags
- [Django]-Django content-type : how do I get an object?
- [Django]-Django datetime issues (default=datetime.now())
0👍
(I am using Pycharm, I also tried every solution in here and found out that the solutions works on some codes and some doesn’t so I just did this solution)
The easiest Resolution that I did is I deleted the LIB where the installed sitepackages are, opened python interpreter in the settings and then it gave me an option where the program(Pycharm) installed the pip/sitepackges and I reinstalled the rest of the packges for example rest_framewrok etc. in the virtual environment of the project using cmd(or any command prompt tool) and it fixed my problem.
- [Django]-Do we need to upload virtual env on github too?
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
- [Django]-How to set a Django model field's default value to a function call / callable (e.g., a date relative to the time of model object creation)
0👍
I used a web service to generate a random key: https://djecrety.ir/
It had multiple dollar signs in it and ruined my manage.py runs. Pycharm’s Run Configuration worked fine with it.
- [Django]-Embed YouTube video – Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
- [Django]-Inline in ModelForm
- [Django]-Django-nonrel + Django-registration problem: unexpected keyword argument 'uidb36' when resetting password
0👍
In my case nothing worked because I source
-ed .env
file. I was able to see the values of the variable with echo $SECRET_KEY
but python process didn’t see it. This happens because it isn’t exported, so I had to export all values with the following command:
eval $(egrep -v '^(#|$)' .env | sed 's|^|export |')
- [Django]-How to perform OR condition in django queryset?
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
0👍
Since Django 3.0 , the AdminEmailHandler
logging handler can raise this, since it tries to read the default reporter_class
from settings – which creates a kind of circular dependency issue.
A solution is to set the reporter_class
in the config of the handler:
"mail_admins": {
"level": "ERROR",
"class": "django.utils.log.AdminEmailHandler",
"reporter_class": "django.views.debug.ExceptionReporter",
},
Source: https://code.djangoproject.com/ticket/32016#comment:9
- [Django]-Adding to the "constructor" of a django model
- [Django]-Where's my JSON data in my incoming Django request?
- [Django]-How to use Django ImageField, and why use it at all?