在处理表单提交时,我必须执行自定义逻辑(联系Web服务等)。如果失败,我想阻止创建模型Car的新实例。
让我们通过一个简单的片段演示:
from django.views import generic
from django.http import HttpResponseRedirect
class CarCreateView(generic.edit.CreateView):
model = Car
form_class = CarForm
def form_valid(self, form):
# some logic that may succeed or fail
if success:
messages.success(self.request, 'bla bla')
return super().form_valid(form)
else:
messages.error(self.request, 'blabla')
# How to return to form index without saving???
return HttpResponseRedirect(self.get_success_url())
不调用super().form_valid(form)
是不够的。一辆新车仍在保存中。有什么想法吗?
答案 0 :(得分:2)
其实我一直都错了。愚蠢的错误。当我保存新实例时,执行从未达到过这一点。
对于任何寻找相同问题的人来说,更清晰的处理方法似乎是
return self.render_to_response(self.get_context_data(form=form))
。
因此代码看起来像:
from django.views.generic import CreateView
from django.http import HttpResponseRedirect
class CarCreateView(CreateView):
model = Car
form_class = CarForm
def form_valid(self, form):
# some logic that may succeed or fail
if success:
messages.success(self.request, 'bla bla')
return super(CarCreateView, self).form_valid(form)
else:
messages.error(self.request, 'blabla')
return self.render_to_response(self.get_context_data(form=form))
这样我们就可以返回相同的表单页面,而无需创建新的实例。
答案 1 :(得分:1)
from django.views.generic import CreateView
from django.http import HttpResponseRedirect
class CarCreateView(CreateView):
model = Car
form_class = CarForm
def form_valid(self, form):
# some logic that may succeed or fail
if success:
messages.success(self.request, 'bla bla')
return super(CarCreateView, self).form_valid(form)
else:
messages.error(self.request, 'blabla')
return super(CarCreateView, self).form_invalid(form)