Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

python - Custom functions in __init__.py cause Django Apps Aren't Installed Yet Error

I have a setup like the following

    Tasks
      |__ __init__.py
      |__ a.py
      |__ b.py
      |__ c.py
         ...

Inside the __init__.py file,

    from .a import custom1, custom2
    from .b import custom3, custom4

I wrote a function within Tasks which requires Tasks to be added as an INSTALLED_APP.

The custom functions however raise django.core.exceptions.AppRegistryNotReady: "Apps aren't loaded yet.".

The traceback leads to a point where one of the custom functions try to import

from django.contrib.auth.models import User.

Why does this happen, and is there a way to fix this error WITHOUT moving the custom functions out of the __init__.py file?

question from:https://stackoverflow.com/questions/65947477/custom-functions-in-init-py-cause-django-apps-arent-installed-yet-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Order of Django initialization is well documented

1.) First Django imports each item in INSTALLED_APPS.

At this stage, your code shouldn’t import any models!

...

3.)Finally Django runs the ready() method of each application configuration.

And futher as documented in 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.

class RockNRollConfig(AppConfig):
# ...

    def ready(self):
        # importing model classes
        from .models import MyModel  # or...
        MyModel = self.get_model('MyModel')

        # registering signals with the model's string label
        pre_save.connect(receiver, sender='app_label.MyModel')

You might consider use of get_model inside of your function that would replace import with require_ready false

But I am not certain it would work depending on your use case


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...