Dorian Amouroux
Dorian Amouroux

Reputation: 157

Execute code after Django init

I have a bunch of apps, that may or may not contains a file called activity.py. This file basically registers model signals. It works well when I import this file in the ready method of the AppConfig class. The problem is I have a dozen app, so I don't want to have this same method in all my apps :

def ready(self):
    # register signal for activity feed
    from . import activity

I would like to run a script that will through the INSTALLED_APPS array, and if this app contains a file activity.py, import it.
I can't find a way to run a function for when all the apps are ready, and before the server is listening.

Upvotes: 1

Views: 1665

Answers (2)

Antonis Christofides
Antonis Christofides

Reputation: 6939

One thing you can do is create another app whose only purpose will be to perform that initialization and put it in INSTALLED_APPS. In that app, subclass AppConfig and override the AppConfig.ready() method.

Upvotes: 1

NS0
NS0

Reputation: 6096

You can try to use the following approach:

from django.conf import settings
from importlib import import_module

for app in settings.INSTALLED_APPS:
    module_name = '%s.%s' % (app, "activity")
    try:
        import_module(module_name)
    except ImportError:
        pass

Upvotes: 0

Related Questions