3

Porting my app to django 1.9, I got the scary django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

Basically my stacktrace is:

  manage.py
    execute_from_command_line(sys.argv)
  django/core/management:352, in execute_from_command_line
    utility.execute()
  django/core/management/__init__.py:326, in execute
    django.setup()
  django/__init__.py:18, in setup
    apps.populate(settings.INSTALLED_APPS)
  django/apps/registry.py:85, in populate
    app_config = AppConfig.create(entry)
  django/apps/config.py:90, in create
    module = import_module(entry)
  python2.7/importlib/__init__.py:37, in import_module
    __import__(name)
  myapp/mylib/__init__.py:52, in <module>
    from django.contrib.contenttypes.models import ContentType   #<= The important part
  django/contrib/contenttypes/models.py:159, in <module>
    class ContentType(models.Model):
  django/db/models/base.py:94, in __new__
    app_config = apps.get_containing_app_config(module)
  django/apps/registry.p:239, in get_containing_app_config
    self.check_apps_ready()
  django/apps/registry.py:124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

My main question here :

Should I import my models in the __init__.py of my django apps ?

It seems to trigger the django.models.ModelBase metaclass that check if the app is ready before creating the model.

damio
  • 6,041
  • 3
  • 39
  • 58

1 Answers1

13

Should I import my models in the __init__.py of my django apps ?

No, you must not import any model in the __init__.py file of any installed app. This is no longer possible in 1.9.

From the release notes:

All models need to be defined inside an installed application or declare an explicit app_label. Furthermore, it isn’t possible to import them before their application is loaded. In particular, it isn’t possible to import models inside the root package of an application.

knbk
  • 52,111
  • 9
  • 124
  • 122