[Django]-I m confused about the ready function used inside app.py

7๐Ÿ‘

โœ…

what is the need of ready function here and why is it importing signals here?

The ready() method [Django-doc] is called after the registry is fully loaded. You thus can then perform some operations you want to perform before the server starts handling requests. This is specified in the documentation:

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

The reason the signals are imported here is because Django will not import the signals if you do not import those explicitly. If the signals module is not imported, then the signals are not registered on the corresponding models, and hence if you for example make changes to your User model, the signals will not be triggered.

Usually one adds a #noqa comment to the import line, to prevent a linter tool like pylint to raise warnings about an import that you do not use.

from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals  # noqa

Leave a comment