Search code examples
djangodjango-signals

Passing the self parameter to a django callback


I want to check if the model attributes make_initial_plan, make_default_plan going to be set in the model to be safe and if so to make unset all the attribute on all other model instances but I don't know how to pass the self parameter to the call back

@receiver(pre_save)
def desactivar_default_o_initial(sender, instance, **kwargs):
    if self.make_initial_plan == True:
        for item in Plan.objects.all():
            item.make_initial_plan = False
            item.save(firstTimePass=False)
    if self.make_default_plan == True:
        for item in Plan.objects.all():
            item.make_default_plan = False
            item.save(firstTimePass=False)

Any Ideas, help in advance


Solution

  • In signals there is no self because they are not class methods. You should use sender for getting class who sends the signal, and instance for the object itself (i.e. that's what you need here)

    Also, I think you should provide a sender argument to signal connector. In current setup your handler will be used for any django model ever.