Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments django signals - post_save/pre_save

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?

like image 763
Mo J. Mughrabi Avatar asked Apr 10 '14 21:04

Mo J. Mughrabi


People also ask

Where is Pre_save signal in Django?

pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.

What is Post_save in Django?

In the example above, save_profile is our receiver function, User is the sender and post_save is the signal. You can read it as: Everytime when a User instance finalize the execution of its save method, the save_profile function will be executed. If you supress the sender argument like this: post_save.

How do you write signals in Django?

There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.

What is the use of the Post_delete signal in Django?

Django Signals - post_delete()To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.


1 Answers

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 
like image 102
Eugene Soldatov Avatar answered Sep 19 '22 06:09

Eugene Soldatov