如果Generic View成功,则调用一些函数

时间:2017-10-27 08:06:57

标签: python django django-class-based-views django-generic-views class-based-views

我在项目中使用通用视图/基于类的视图,如果视图成功完成,我想调用一些函数。我用这个def get_success_url()方法。但是我无法在该功能中达到模型。我怎么能摆脱这个,还是有其他方法可以做到这一点?

我的代码:

class MyModelUpdate(UpdateView):
    model = MyModel
    fields = ['details']

    def get_success_url(self, **kwargs):
        add_log(form.model, 2, 1, request.POST.user)
        return reverse_lazy('model-detail', kwargs = {'pk' :  self.kwargs['model_id'] })

1 个答案:

答案 0 :(得分:2)

UpdateView类实现UpdateMixin,其中包含form_valid等方法,仅在表单数据有效时才会调用。

所以你可以这样做:

class MyModelUpdate(UpdateView):
    model = MyModel
    fields = ['details']

    def get_success_url(self, **kwargs):
         return reverse_lazy('model-detail', kwargs={'pk': self.kwargs['model_id']})

    def form_valid(self, form):
        # The super call to form_valid creates a model instance
        # under self.object.
        response = super(MyModelUpdate, self).form_valid(form)

        # Do custom stuff here...
        add_log(self.object, 2, 1, self.request.POST.user)

        return response