0

I'm upgrading from django 1.6.5 to django 1.9, and in the process upgrading several middleware classes. Some of those middleware classes use models during the process_request or process_response phases. However, I'm getting a AppRegistryNotReady: Apps aren't loaded yet. error attempting to use them.

Is there a way to import models during middleware?
Should I move my import statements into the process_request / process_response methods?

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/newrelic-2.50.0.39/newrelic/api/web_transaction.py", line 1329, in _nr_wsgi_application_wrapper_
    result = wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/newrelic-2.50.0.39/newrelic/api/web_transaction.py", line 1329, in _nr_wsgi_application_wrapper_
    result = wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 158, in __call__
    self.load_middleware()
  File "/usr/local/lib/python2.7/dist-packages/newrelic-2.50.0.39/newrelic/common/object_wrapper.py", line 302, in _wrapper
    result = wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 51, in load_middleware
    mw_class = import_string(middleware_path)
  File "/usr/local/lib/python2.7/dist-packages/django/utils/module_loading.py", line 20, in import_string
    module = import_module(module_path)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/web/MyJobs/MyJobs/apache/../middleware.py", line 9, in <module>
    from django.contrib.sites.models import Site
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/sites/models.py", line 83, in <module>
    class Site(models.Model):
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 94, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 239, in get_containing_app_config
    self.check_apps_ready()
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
AppRegistryNotReady: Apps aren't loaded yet.
mklauber
  • 1,126
  • 10
  • 19
  • This is probably a problem with your `wsgi.py`. Are you using `get_wsgi_application()` or the old `WSGIHandler()`? – knbk Nov 17 '16 at 19:49
  • @knbk Thanks. I was using the old handler. Make an answer and I'll accept it. – mklauber Nov 17 '16 at 19:52

1 Answers1

1

You need to use the new API to get a WSGI handler:

from django.core.wsgi import get_wsgi_application

application = get_wsgi_application()

This will call django.setup() for you, which will populate the app registry.

knbk
  • 52,111
  • 9
  • 124
  • 122