2

i m doing some project using django frame work i am a beginner and just used django signals but i m confused that why do we need to imporrt signals file in app.py inside the ready function

code below makes question more clear i m stuck in this so require help

signal.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save,sender=User)
def save_profile(sender,instance,**kwargs):
    instance.profile.save()

app.py

from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals
        #i have no idea what this function does

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

what if i import signals at the top without using ready function??

Aayush Neupane
  • 1,066
  • 1
  • 12
  • 29

1 Answers1

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555