I want to run some code after my model is saved. Three places to do this will be
1) override save method:
def save(self, *args, **kwargs): super(Blog, self).save(*args, **kwargs) do_something() 2) use post_save signal:
def model_created(sender, **kwargs) the_instance = kwargs['instance'] if kwargs['created']: do_something() post_save.connect(model_created, sender=YourModel) 3) do this in the view itself.
if form.is_valid(): do_something() return redirect(reverse("homepage")) All three should work. This post advocates the second one.
My question is that the second method (post_save) works when the model is first created. I want to call do_something() whenever a new model is created and also when an existing model is updated. In the latter case, I will have kwargs[created] to be false. how do I handle this situation?
P.S: I am currently doing the third one which works fine for both updateView and CreateView. but the problem is it takes time to return from the do_something() function before it is being redirected.
if kwargs['created']check in thepost_savesignal handler?if kwargs['created']check anddo_something()would be called whenever model is created or updated.