Passing arguments django signals - post_save/pre_save

Mo J. Mughrabi picture Mo J. Mughrabi · Apr 10, 2014 · Viewed 14.3k times · Source

I am working on a notification app in Django 1.6 and I want to pass additional arguments to Django signals such as post_save. I tried to use partial from functools but no luck.

from functools import partial
post_save.connect(
    receiver=partial(notify,
        fragment_name="categories_index"),
            sender=nt.get_model(),
            dispatch_uid=nt.sender
    )

notify function has a keyword argument fragment_name which I want to pass as default in my signals.

Any suggestions?

Answer

Eugene Soldatov picture Eugene Soldatov · Apr 18, 2014

You can define additional arguments in custom save method of model like this:

class MyModel(models.Model):
    ....

    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)
        self.my_extra_param = 'hello world'

And access this additional argument through instance in post_save signal receiver:

@receiver(post_save, sender=MyModel)
def process_my_param(sender, instance, *args, **kwargs):
    my_extra_param = instance.my_extra_param