在 Django 中注册信号导致 "Apps aren't loaded yet." 错误

registering signals in Django results in "Apps aren't loaded yet." error

我在尝试导入信号时不断收到错误消息:

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

我无法理解,b/c 我在其他应用程序中设置用户配置文件时成功地使用了以下模式:

models.py:

from django.conf import settings
from django.db import models

class UserProfile(models.Model):
  user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    

signals.py:

from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from my_project.my_app.models import UserProfile

def post_save_user_hander(sender, *args, **kwargs):
     created = kwargs.get("created", False)
     instance = kwargs.get("instance", None)
     if created and instance:
         UserProfile.objects.create(user=instance)


post_save.connect(
    post_save_user_hander, 
    sender=get_user_model(),
    dispatch_uid="post_save_user_handler",
)

app.py:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_project.my_app'

    try:
        import my_project.my_app.signals  
    except ImportError:
        pass

根据 the documentationready() 被称为“一旦注册表完全填充”。因此, UserProfile 的导入不应该成功吗? 还有,文档说明

Although you can’t import models at the module-level where AppConfig classes are defined, you can import them in ready(), using either an import statement or get_model().

因此,将它们包含在 signals.py 的顶部,它本身在 ready() 中导入应该可行,对吧?

尝试在 AppConfig.ready 方法中包含信号。

from django.apps import AppConfig


class MyAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_project.my_app'

    def ready(self):
        import my_project.my_app.signals

来自docs on AppConfig.ready

Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.

If you’re registering model signals, you can refer to the sender by its string label instead of using the model class itself.

所以,我认为在 AppConfig.ready 方法中包含信号是一种常见的方法。