Django CreateView: How to perform action upon save
Solution 1:
The form_valid()
method for CreateView
and UpdateView
saves the form, then redirects to the success url. It's not possible to do return super()
, because you want to do stuff in between the object being saved and the redirect.
The first option is to not call super()
, and duplicate the two lines in your view. The advantage of this is that it's very clear what is going on.
def form_valid(self, form):
self.object = form.save()
# do something with self.object
# remember the import: from django.http import HttpResponseRedirect
return HttpResponseRedirect(self.get_success_url())
The second option is to continue to call super()
, but don't return the response until after you have updated the relationship. The advantage of this is that you are not duplicating the code in super()
, but the disadvantage is that it's not as clear what's going on, unless you are familiar with what super()
does.
def form_valid(self, form):
response = super(CourseCreate, self).form_valid(form)
# do something with self.object
return response
Solution 2:
I would suggest to use Django's Signal. That is an action that gets triggered when something happens to a Model, like save or update. This way your code stays clean (no business logic in the form-handling), and you are sure that it only gets triggered after save.
#views.py
from django.dispatch import receiver
...
@receiver(post_save, sender=Course)
def post_save_course_dosomething(sender,instance, **kwargs):
the_faculty = instance.faculty
#...etc