Accessing a django model in middleware (django>1.7) - django

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.

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.

Related

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.- django 1.11

After trying to implement Token Authentication using DRF, i get this error raised in my terminal. I have had seen other related relevant questions with solutions but none of them solved my issue.
Below is my wsgi.py
"""
WSGI config for myApp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myApp.settings")
application = get_wsgi_application()
stack trace
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute
django.setup()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/emmnock/Desktop/peaceAppProject/peaceApp/peace/models.py", line 28, in <module>
Token.objects.get_or_create(user=user)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 464, in get_or_create
return self.get(**lookup), False
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 371, in get
clone = self.filter(*args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 782, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 800, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1261, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1165, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1045, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1342, in names_to_path
if field.is_relation and not field.related_model:
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/fields/related.py", line 115, in related_model
apps.check_models_ready()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/registry.py", line 132, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Try editing your wsgi.py like this,
import os
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = get_wsgi_application()

Can't access models from the script initialized in init.py

Can U tell me how to access models before all the apps gets loaded
This is my mqtt.py which was initialized in init.py and accessing
models
import paho.mqtt.client as mqtt
from Transport.models import BusPosition
# Broker CONNACK response
def on_connect(client,userdata,flags,rc):
print ("Connected with result code "+str(rc))
# Subcribing to topic and recoonect for
client.subscribe("trackrkct")
#Receive message
def on_message(client,userdata,msg):
print(msg.topic+" "+str(msg.payload))
BusPosition.create(1, "Mon, 23 May 2016 08:30:15 GMT", 11.0998, 77.9098)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com",1883,60)
This is my init.py where mqtt.py was initialized
from kctsmarttransport import mqtt
mqtt.client.loop_start()
and this is my models.py
from __future__ import unicode_literals
from django.db import models
class BusPosition(models.Model):
bus = models.ForeignKey(Bus)
time = models.DateTimeField
lat = models.FloatField(max_length=20)
lng = models.FloatField(max_length=20)
#classmethod
def create(cls,bus,time,lat,lng):
busPosition = cls(bus=bus,time=time,lat=lat,lng=lng)
busPosition.save()
return busPosition
and I got these errors as apps aren't loaded yet
"C:\Program Files (x86)\JetBrains\PyCharm 2016.2.3\bin\runnerw.exe" C:\Users\Navin\DjangoProject\kct_transport_env\Scripts\python.exe C:/Users/Navin/DjangoProject/kctsmarttransport/manage.py runserver 5000
Traceback (most recent call last):
File "C:/Users/Navin/DjangoProject/kctsmarttransport/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\core\management\__init__.py", line 316, in execute
settings.INSTALLED_APPS
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
self._setup(name)
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\conf\__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\conf\__init__.py", line 97, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\Navin\DjangoProject\kctsmarttransport\kctsmarttransport\__init__.py", line 1, in <module>
from kctsmarttransport import mqtt
File "C:\Users\Navin\DjangoProject\kctsmarttransport\kctsmarttransport\mqtt.py", line 2, in <module>
from Transport.models import BusPosition
File "C:\Users\Navin\DjangoProject\kctsmarttransport\Transport\models.py", line 6, in <module>
class Bus(models.Model):
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\db\models\base.py", line 105, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config
self.check_apps_ready()
File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\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.
Process finished with exit code 1

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

I have upgraded django version from 1.8 into 1.9 and django rest framework to 3.3.3. I am getting this exception:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I have tried as follows but exception is still there.
#__init__.py
default_app_config = 'panel.apps.PanelConfig'
And also
#apps.py
from django.apps import AppConfig
class PanelConfig(AppConfig):
name = 'panel'
def ready(self):
from panel import receivers
for all apps and added these to installed apps
'api.apps.ApiConfig',
'billing.apps.ApiConfig',
'incoming.apps.IncomingConfig',
'outgoing.apps.OutgoingConfig',
'panel.apps.PanelConfig',
This is my full traceback:
Unhandled exception in thread started by <function wrapper at 0x7f3eec09c7d0>
Traceback (most recent call last):
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/admin_tools/dashboard/__init__.py", line 1, in <module>
from admin_tools.dashboard.dashboards import *
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/admin_tools/dashboard/dashboards.py", line 13, in <module>
from django.contrib.contenttypes.models import ContentType
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 161, in <module>
class ContentType(models.Model):
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/db/models/base.py", line 94, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/django/apps/registry.py", line 239, in get_containing_app_config
self.check_apps_ready()
File "/home/sparrow/virtualenvs/bishnu/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.
Exception is still there ? What is the problem ? I am not getting ?
The traceback shows you that the problem is occuring in admin_tools.
from admin_tools.dashboard.dashboards import *
File "/home/sparrow/virtualenvs/bishnu/local/lib/python2.7/site-packages/admin_tools/dashboard/dashboards.py", line 13, in <module>
from django.contrib.contenttypes.models import ContentType
It looks like it has been fixed, so try upgrading to the latest release, currently 0.7.2.

migrate failure (django 1.8)

I'm trying in vain to migrate my database to the server. here is the traceback that I get from the terminal.
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv) File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute() File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/core/management/__init__.py", line 328, in execute
django.setup() File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS) File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models) File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name) File "/home/guimatsi/lib/python2.7/registration/models.py", line 15, in <module>
User = get_user_model() File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/contrib/auth/__init__.py", line 150, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL) File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/apps/registry.py", line 199, in get_model
self.check_models_ready() File "/home/guimatsi/webapps/nnmland/lib/python2.7/Django-1.8.6-py2.7.egg/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Since I'm new in django and it's my first project, Every hint would be appreciated. ths in advance.
It looks like you might be using a version of Django registration that does not support Django 1.8. You could try installing Django registration redux instead.

Django 1.7 upgrade error: AppRegistryNotReady using serializers from rest_framework

I get this traceback:
Traceback (most recent call last):
File "./manage.py", line 38, in <module>
execute_from_command_line(sys.argv)
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/apps/config.py", line 197, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/mgregory/Documents/cm_central/cmh_server/models.py", line 88, in <module>
class VersionSerializer(serializers.ModelSerializer):
File "/Users/mgregory/Documents/cm_central/cmh_server/models.py", line 89, in VersionSerializer
brzs= BrzSerializer(many=True)
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/rest_framework/serializers.py", line 198, in __init__
self.fields = self.get_fields()
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/rest_framework/serializers.py", line 234, in get_fields
default_fields = self.get_default_fields()
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/rest_framework/serializers.py", line 732, in get_default_fields
reverse_rels = opts.get_all_related_objects()
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/db/models/options.py", line 498, in get_all_related_objects
include_proxy_eq=include_proxy_eq)]
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/db/models/options.py", line 510, in get_all_related_objects_with_model
self._fill_related_objects_cache()
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/db/models/options.py", line 533, in _fill_related_objects_cache
for klass in self.apps.get_models(include_auto_created=True):
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/utils/lru_cache.py", line 101, in wrapper
result = user_function(*args, **kwds)
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/apps/registry.py", line 168, in get_models
self.check_models_ready()
File "/Users/mgregory/Documents/virtualenvs/cm_central/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
from this code (models.py):
# Serializers for transmitting CMx install information over HTTP
class BrzSerializer(serializers.ModelSerializer):
class Meta:
model = Brz
fields=('filename',)
class VersionSerializer(serializers.ModelSerializer):
brzs= BrzSerializer(many=True)
class Meta:
model = Version
fields=('name', 'for_mac', 'for_windows', 'brzs')
It sounds like it's telling me "your VersionSerializer can't have a BrzSerializer, because you haven't registered that yet".
I've looked at other SO questions relating to AppRegisteryNotReady, but didn't find one that matches this symptom. Surely I have to be able to define a chain of dependent models like this?
It turns out that having the declaration of the serializers inside models.py is causing that application to be used before the app registry has finished being loaded.
models.py is actually the wrong place to declare these serializers (though I'm 99% certain I did it that way based on an example of how to use them).
The fix is to move the declaration of the serializers out into their own file (which makes sense, because they have nothing to do with the database schema, which models.py is defining), and import that from the view. By the time the view gets going, the app registry is ready.