Search code examples
djangodjango-haystack

Signal called in settings importing an app : failed


I am using Python 3.4.3, Django 1.9.2 and django-haystack 2.4.1.

I only put the essential code to explain.

Here is my settings :

INSTALLED_APPS = (
    ...,
    contacts.documents,
    haystack,
    contacts.search,
)

HAYSTACK_SIGNAL_PROCESSOR = 'contacts.search.signals.MyRealtimeProcessor'

Here is my file : contacts.search.signals.py :

from contacts.documents.models import Document

class MyRealtimeProcessor(RealtimeSignalProcessor):

    def handle_save(self, sender, instance, **kwargs):
        …
        d_index = self.connections[using].get_unified_index()\
                                                 .get_index(Document)

With this code I obtain the error :

 raise AppRegistryNotReady("Apps aren't loaded yet.")

Because of from contacts.documents.models import Document in my signal.

How can I correct it?


Solution

  • You cannot load models before Django has finished loading all apps. It's not entirely clear to me why your signals.py file is being imported before the apps are loaded, but you can get around this by moving this logic into the __init__ method of your class:

    def __init__(self, *args, **kwargs):
        from contacts.documents.models import Document
    
        self.document_model = Document
        super(MyRealtimeProcessor, self).__init__(args, kwargs)
    

    and then in handle_save:

    d_index = self.connections[using].get_unified_index()\
                                                 .get_index(self.document_model)