0

While messing around with signals I discovered that Django does not load the apps until some point after the app's __init__.py runs, which makes sense. But, when does Django load the apps? Here is the code that led me here, all part of an app called imt_prod:

__init__.py

import imt_prod.signals

signals.py

from django.contrib.auth.signals import user_logged_in

# This produces 'django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.'
from imt_prod.models import LoginHistory

def recordLogon(sender, user, request, **kwargs):
    from imt_prod.models import LoginHistory  # This does not
    LoginHistory.objects.get_or_create(User=user)

user_logged_in.connect(recordLogon)

models.py

from django.contrib.auth.models import User
from django.db import models

class LoginHistory(models.Model):
    User = models.OneToOneField(User, null=False, blank=False, on_delete=models.SET("USER DELETED"), verbose_name="User")
    date = models.DateField(default=date.today, null=False, blank=False, verbose_name="Logon Date")
MackM
  • 2,906
  • 5
  • 31
  • 45
  • 2
    Import the signals in the app config's `ready()` method, as in [this answer](https://stackoverflow.com/questions/7115097/the-right-place-to-keep-my-signals-py-file-in-a-django-project/21612050#21612050). – Alasdair Mar 11 '20 at 17:36
  • 2
    I would avoid putting code in the `__init__.py` for Django apps. The `__init__.py` will be loaded before any of the app's modules like `models.py` which leads to issues. – Alasdair Mar 11 '20 at 17:37

0 Answers0