Skip to content
Advertisement

About (sender, instance, created, **kwargs) parameter. How it’s assigned

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)

I’m new to python in general and while I was going through a tutorial it teaches about signals.

I’ve been trying to figured how this function works, as in how (sender, instance, created, **kwargs) is assigned to? I can’t seem to wrap my head around it.

So if a post is saved it triggers this vvv

receiver(post_save, sender=User)

in this case User gets assigned to sender, since sender=User easy.

Now, as for the second parameter, instance, it shows in the very last line of the function. user=instance. from my understanding of function, and parameter, should it all be assigned WHEN the function is CALLED? in this case when the receiver signal is triggered and create_profile is called, instance and created has no value yet…. correct? As for created, why does it have to be a parameter? since it’s checking if CREATED.

Does (instance, created) have an in built….functionality in it? since from what I get those three are placeholders and it needs to be assigned a value in order to do anything. When does instance and created get assigned? And what is ‘if created’? I understand that means if the aaccount is created but HOW does the created parameter hold a value to work in this if created to work?

In the future, if I encounter similar problems such as this…how can I figure out how it works?

Advertisement

Answer

The parameters mean the following:

sender: The model class which the signal was called with.

instance: The instance of a User, whether this was created or updated.

created: A Boolean to determine if the User was updated or created.

When the signal is called, none of the parameters will be empty.

I found this information on the official Django docs page.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement