Django CreateView: How to perform action upon save

后端 未结 2 1111
小蘑菇
小蘑菇 2020-12-03 01:22

I\'m using a custom CreateView (CourseCreate) and UpdateView (CourseUpdate) to save and update a Course. I want to take an action when the Course is saved. I will create a n

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 01:43

    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
    

提交回复
热议问题