我在项目中使用通用视图/基于类的视图,如果视图成功完成,我想调用一些函数。我用这个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'] })
答案 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