Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin, Call function on save

Tags:

python

django

I have a app in my Django site that handles blog post. When a blog post is published I want to schedule a Newsletter on a third party application that informs the subscribers of the new post.

So I want to add a custom function to be called when the blog post is saved where I can write this API call to the newsletter service.

How to do this? Tried looking through the documentations and all I can find is Admin Actions which doesn't seem to be what I'm looking for.

like image 419
Marcus Lind Avatar asked May 15 '15 06:05

Marcus Lind


2 Answers

There are a number of approaches you could use.

Override the model save method is simple, but will be called every time the model is saved.

https://docs.djangoproject.com/en/dev/ref/models/instances/#saving-objects

If it is specific to the admin site, in your ModelAdmin use the model_save() method. (I like this approach personally, as it won't interfere with your model).

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model

You could also use a post save signal, but save methods seem to be preferred (depending on what you are doing) Django: When to customize save vs using post-save signal

like image 125
wobbily_col Avatar answered Nov 12 '22 20:11

wobbily_col


You should definitely go for https://docs.djangoproject.com/en/1.8/ref/signals/#django.db.models.signals.post_save, which provides the complete functionality that you are looking for here.

like image 2
Abhishek Agarwala Avatar answered Nov 12 '22 18:11

Abhishek Agarwala