135

When upgraded to django 1.9 from 1.8 I got this error. I checked answers for similar questions, but I didn't think this is an issue with any 3rd party packages or apps.

Traceback (most recent call last):
File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 176, in fetch_command
commands = get_commands()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 100, in wrapper
result = user_function(*args, **kwds)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 71, in get_commands
for app_config in reversed(list(apps.get_app_configs())):
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I'd modified the Installed apps for 'django.contrib.auth'.

Kishore K
  • 2,425
  • 4
  • 18
  • 18
  • 1
    are you using any third party app? Please share your settings.py – utkbansal Dec 06 '15 at 05:37
  • I'm using many 3rd party apps, but I believe this error is raised from "django/apps/registry.py" and not from any other apps in site packages. – Kishore K Dec 06 '15 at 05:40
  • 2
    I have faced a similar issue with django-crispy-forms because the ibrary doesnt support 1.9 yet. So this might be an unsupported app. – utkbansal Dec 06 '15 at 05:41
  • 1
    I'm not using that package. Sorry If I'm wrong, if it is related to any packages, the trace will be pointing to that app in site packages, right? – Kishore K Dec 06 '15 at 05:44
  • Same payu not support 1.9 – GrvTyagi May 25 '16 at 11:17
  • I had the same issue. The problem was that in my console I run python and import models there instead of ./manage.py shell and then calling model – Rustam Aug 03 '19 at 05:36

32 Answers32

174

Try to add this lines to the top of your settings file:

import django
django.setup()

And if this will not help you try to remove third-party applications from your installed apps list one-by-one.

inlanger
  • 2,904
  • 4
  • 18
  • 30
  • 12
    I tried it, but i got this error "django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty." Even though I've the SECRET_KEY in settings file. – Kishore K Dec 06 '15 at 12:12
  • 12
    Try declaring the SECRET_KEY **BEFORE** the mentioned lines, something like: SECRET_KEY = 'MY SECRET KEY' import django django.setup() it worked for me.... now with another error :) – Duda Nogueira Dec 07 '15 at 10:59
  • 1
    This is a great answer to question: "How do I access Django model objects from a stand alone script?" :-) Before run the code above, you will need to do: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your.settings") though. – AdvilUser Jul 08 '16 at 21:58
  • 1
    Didn't work on settings but works on my standalone script. This exception also happens if you forget to call django.setup() in a standalone Python script. https://docs.djangoproject.com/en/1.10/ref/applications/#troubleshooting – André Duarte Feb 20 '17 at 13:59
  • 52
    **`django.setup()` is for use in stand alone scripts. You shouldn't put it in settings** – Alasdair Apr 04 '18 at 17:27
  • To reiterate what @Alasdair has said, this is from the docs: `If you’re using components of Django “standalone” – for example, writing a Python script which loads some Django templates and renders them, or uses the ORM to fetch some data – there’s one more step you’ll need in addition to configuring settings.` – TheRealFakeNews May 14 '19 at 15:01
  • [django.setup in documentation](https://docs.djangoproject.com/en/3.0/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage) – djvg Jun 25 '20 at 12:53
52

I'd a custom function written on one of my models __init__.py file. It was causing the error. When I moved this function from __init__.py it worked.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
Kishore K
  • 2,425
  • 4
  • 18
  • 18
50

My problem was that I tried to import a Django model before calling django.setup()

This worked for me:

import django
django.setup()

from myapp.models import MyModel

The above script is in the project root folder.

M3RS
  • 6,720
  • 6
  • 37
  • 47
18

In my case, the error occurred when I made python manage.py makemigrations on Django 2.0.6.

The solution was to run python manage.py runserver and see the actual error (which was just a missing environment variable).

Pavel Vergeev
  • 3,060
  • 1
  • 31
  • 39
12

This error may occur when you are adding an app in INSTALLED_APPS in the settings.py file but you do not have that app installed in your computer. You have two solution:

  1. Install that app using package managers like pip in ubuntu
  2. Or Comment out that installed app in the settings.py file

This error may also arise if you are not in your virtual environment which you may have created for your project.

Amrit
  • 2,115
  • 1
  • 21
  • 41
11

I think this wasn't mentioned yet, but is a common cause for the error: The error occurs when you specify startup code that uses models. If you follow this approach and put it into your AppConfig you must not import models at the top of the file, but inside the ready() method. For example as follows:

# works as models are imported in the ready() method
from django.apps import AppConfig

class MatcherConfig(AppConfig):
    name = 'matcher'
    verbose_name = 'Match-Making'
    def ready(self):
        from matcher.background_tasks import close_timeout_games
        from matcher.models import FourPlayerGame
        # check if a player is not responding every 5 seconds
        close_timeout_games(FourPlayerGame, repeat=5)

However, the following would be wrong:

# won't work as models are imported at the beginning
from django.apps import AppConfig
from matcher.background_tasks import close_timeout_games
from matcher.models import FourPlayerGame

class MatcherConfig(AppConfig):
    name = 'matcher'
    verbose_name = 'Match-Making'
    def ready(self):
        # check if a player is not responding every 5 seconds
        close_timeout_games(FourPlayerGame, repeat=5)

For more information also see this answer.

F.M.F.
  • 1,929
  • 3
  • 23
  • 42
  • Thanks. This is the best answer for my case. Moving `imports` inside of `def ready(self)` is what I needed. – Masoud Gheisari Nov 15 '22 at 08:11
  • This is the most correct, general and elegant answer. The other answers address specific instances of this, or usage in external scripts which is not OP's issue. – sox supports the mods Jan 11 '23 at 10:54
  • 1
    I hate deferring imports to local scope, but I found Django already does this. I spent two frustrating hours trying every other solution and wishing I had already built CI/CD to test for this type of failure. Thanks. – John Jul 15 '23 at 12:12
8

First import and run django.setup() before importing any models


All the above answers are good but there is a simple mistake a person could do is that (In fact in my case it was).

I imported Django model from my app before calling django.setup(). so proper way is to do...

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')

import django
django.setup()

then any other import like

from faker import Faker
import random
# import models only after calling django.setup()
from first_app.models import Webpage, Topic, AccessRecord
Himanshu Patel
  • 568
  • 6
  • 14
7

For me, the problem came from the fact that I was importing an app in INSTALLED_APPS which was itself importing a model in its __init__.py file

I had :

settings.py

INSTALLED_APPS = [
    ...
    'myapp',
    ...
]

myapp.__init__.py

from django.contrib.sites.models import Site

commenting out import models in myapp.__init__.py made it work :

# from django.contrib.sites.models import Site
Albyorix
  • 637
  • 1
  • 6
  • 13
  • I have the similar problem. But I need the import in my case. How would you do that? – JohnnyQ Sep 18 '18 at 02:40
  • You can always refactor to avoid importing models from __init__. An option that would work for sure would be to refactor the files importing your app but it might be quite heavy changes. In the end, it's what I had to do! – Albyorix Sep 18 '18 at 12:41
  • Same issue as @JohnnyQ. Works fine in 1.8 but breaks in 1.9. Is there any relevant documentation somewhere around? The exception arises due to import of User from django.contrib.auth.models in my case – Vinod Jan 28 '20 at 04:54
  • Had asked about this in a separate question here https://stackoverflow.com/questions/59927122/django-upgrade-from-1-8-to-1-9-is-breaking-on-model-import-in-init and got the answer. Gist, no other way but to refactor – Vinod Jan 29 '20 at 05:16
5

Try removing the entire settings.LOGGING dictConfig and restart the server. If that works, rewrite the setting according to the v1.9 documentation.

https://docs.djangoproject.com/en/1.9/topics/logging/#examples

pragmar
  • 1,004
  • 9
  • 13
  • Thanks it worked. For me I was using setting files of linux on windows. Hence `/var/log` logfile path dint exist which gave this error – Pratibha Nov 28 '18 at 11:02
5

You may get this error if you've started normal Python shell by mistake and trying to import your Django models in that.

You should instead use python manage.py shell for that.

Krishna
  • 6,107
  • 2
  • 40
  • 43
3

For me commenting out

'grappelli.dashboard',
'grappelli',

in INSTALLED_APPS worked

algometrix
  • 3,704
  • 2
  • 14
  • 22
  • For me it was just that I accidentally had `'one_third_pary_app,'` instead of `'one_third_pary_app',` (note the position of the `,`) – J0ANMM Dec 02 '16 at 15:54
3

django.setup() in the top will not work while you are running a script explicitly. My problem solved when I added this in the bottom of the settings file

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import sys
if BASE_DIR not in sys.path:
    sys.path.append(BASE_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] =  "igp_lrpe.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "igp_lrpe.settings")
import django
django.setup()
2

I put the User import into the settings file for managing the rest call token like this

# settings.py
from django.contrib.auth.models import User
def jwt_get_username_from_payload_handler(payload):
   ....

JWT_AUTH = {
    'JWT_PAYLOAD_GET_USERNAME_HANDLER': jwt_get_username_from_payload_handler,
    'JWT_PUBLIC_KEY': PUBLIC_KEY,
    'JWT_ALGORITHM': 'RS256',
    'JWT_AUDIENCE': API_IDENTIFIER,
    'JWT_ISSUER': JWT_ISSUER,
    'JWT_AUTH_HEADER_PREFIX': 'Bearer',
}
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

Because at that moment, Django libs are not ready yet. Therefore, I put the import inside the function and it started to work. The function needs to be called after the server is started

Thai Tran
  • 9,815
  • 7
  • 43
  • 64
2

I get that error when I try to run test.py(not full scripts, I don't want to use python manage.py test)

and the following method is working for me.

import os
import django
if 'env setting':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YourRoot.settings')
    django.setup()
from django.test import TestCase
...

class SomeTest(TestCase):
    def test_one(self):  # <-- Now, I can run this function by PyCharm
        ...

    def test_two(self):
        ...
Carson
  • 6,105
  • 2
  • 37
  • 45
  • Assuming `DJANGO_SETTINGS_MODULE` is defined, there are 2 important lines of code in this answer; `import django` and `django.setup()`. If one is using objects from a django project in a one-off python script *within* the project, the scope of that script most likely doesn't have access to the django project. By calling the aforementioned lines, you essentially let that script know about the contents of your django project. When I need to call these, I just add them to the top of the script before any other imports. – AdamY Dec 27 '20 at 16:17
1

My problem was: django-reversion>=1.8.7,<1.9

for django 1.9.7 you should use: django-reversion==1.10.0

I were upgraded django-cms 3.2 to 3.3, and found it by commenting apps, then uncommenting back.

Correct answer here: https://stackoverflow.com/a/34040556/2837890

Community
  • 1
  • 1
Anshik
  • 633
  • 8
  • 15
1

This issue is also observed for inconsistent settings.py for incorrectly writing INSTALLED_APPS, verify if you correctly included apps and separated with "," .

Waykos
  • 29
  • 2
1

When I change my django version to 1.9, it don't arise the error. pip uninstall django pip install django==1.9

admin
  • 169
  • 1
  • 6
1

I was in trouble with such matter my problem was because of having this piece of code in settings.py

import myapp.models

when I removed this code problem fixed I recommend check your settings.py and remove such code

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

In my case one of my settings, 'CORS_ORIGIN_WHITELIST' was set in the settings.py file but was not available in my .env file. So I'll suggest that you check your settings, especially those linked to .env

medobills
  • 127
  • 2
  • 6
0

As others have said this can be caused when you've not installed an app that is listed in INSTALLED_APPS.

In my case, manage.py was attempting to log the exception, which led to an attempt to render it which failed due to the app not being initialized yet. By commenting out the except clause in manage.py the exception was displayed without special rendering, avoiding the confusing error.

# Temporarily commenting out the log statement.
#try:
    execute_from_command_line(sys.argv)
#except Exception as e:
#    log.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
#    raise e
John Lehmann
  • 7,975
  • 4
  • 58
  • 71
0

I tried tons of things, but only downgrading Django to 1.8.18 fixed this issue for me:

pip install django==1.8.18

It is one of the installed apps that is failing, but I could not find which one.

oriadam
  • 7,747
  • 2
  • 50
  • 48
0

I get that error when i try to run:

python manage.py makemigrations

i tried so many things and realized that i added some references to "settings.py" - "INSTALLED_APPS"

Just be sure what you write there is correct. My mistake was ".model." instead of ".app."

Corrected that mistake and it's working now.

Castor
  • 1
  • 1
  • 4
0

I've run into this problem and it was rooted in asgi.py. we've loaded the below module:

from channels.auth import AuthMiddlewareStack 

but we didn't use it in the ProtocolTypeRouter. apparently, we have to use websocket or other protocols when we call the AuthMiddlewareStack module.

Ehsan Ahmadi
  • 1,382
  • 15
  • 16
0

For others that might stumble upon this in future:

If you encounter this issue while running Python 3.8 and trying to use multiprocessing package, chances are that it is due to the sub processed are 'spawned' instead of 'forked'. This is a change with Python 3.8 on Mac OS where the default process start method is changed from 'fork' to 'spawn'. This is a known issue with Django.

To get around it:

import multiprocessing as mp
mp.set_start_method('fork')
Oscar Chen
  • 559
  • 5
  • 11
0

I faced this problem when I was trying to load a function in the init file (__init__.py) of my settings package.

The cause of this error

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

is that, before settings were loaded, I wanted to load another module (e.g. rest_framework).

To solve this, I put functions in another module (file) in settings package (e.g. common.py), and it solved the problem.

0

The reason I got this error appregistrynotready is That I accidentally Register User model in app.py instead of admin.py

This is how it's looked like

app.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User

@admin.register(User)
class UserAdmin(BaseUserAdmin):
    pass
  • The issue here is not that you *registered* it, but that you **imported** it. The import is executed when the file is read, and app.py is read before django has setup its models and apps (admin.py is not, that's why it works there) – sox supports the mods Jan 11 '23 at 11:49
0

i faced the same issue when i used

from django.urls import reverse

Solution:

from django.urls import reverse_lazy
-1

Late to the party, but grappelli was the reason for my error as well. I looked up the compatible version on pypi and that fixed it for me.

lslaz
  • 85
  • 11
-1

Try activating the virtual env. In my case, using the git command line tool:

source scripts/activate

Solves my problem.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
-1

Got this error while trying to access model objects in apps.py:

class QuizConfig(AppConfig):
name = 'quiz'

def ready(self):
    print('===============> Django just started....')
    questions_by_category = Question.objects.filter(category=2) # <=== Guilty line of code.

Trying to access Question before the app has loaded the model class caused the error for me.

Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
-2

If your setting.py files fill are correct,you can try to arrive manage.py files proceed call danjgo.setup() in main method . Then run manage.py ,finally again run project ,the issue could disappear.

xing liu
  • 1
  • 1
-2

In the "admin" module of your app package, do register all the databases created in "models" module of the package.

Suppose you have a database class defined in "models" module as:

class myDb1(models.Model):
    someField= models.Charfiled(max_length=100)

so you must register this in the admin module as:

from .models import myDb1
admin.site.register(myDb1)

I hope this resolve the error.

phd
  • 82,685
  • 13
  • 120
  • 165