使用Django的基于类的视图,如果表单无效,如何在返回响应时将状态代码设置为400?这在功能视图中很容易,但是无论形式有效性如何,CBV都会响应200状态。
class CRMContactsAdd(CreateView):
model = models.Contact
fields = ['name','job_title','phone_number','email_address','notes']
template_name = 'crm/add_contact.html'
def get_success_url(self):
return reverse('CRM-list')+"?show_modal_url="+reverse('CRM-contacts',args=())
def get_context_data(self, **kwargs):
cd = super(CRMContactsAdd,self).get_context_data(**kwargs)
cd['company'] = get_object_or_404(models.Company,pk=self.kwargs['pk'])
cd['title'] = "Add contact to %s" % (cd['company'].name)
return cd
def form_valid(self, form):
contact = form.save(commit=False)
contact.company = get_object_or_404(models.Company,pk=self.kwargs['pk'])
return super(CRMContactsAdd,self).form_valid(form)
我之所以想要这样做是因为我可以轻松地使用状态代码来说明是否在模态窗口中重新加载顶级窗口或更新模式w /响应提交表格。
答案 0 :(得分:3)
您可以覆盖form_invalid()
来更改回复的状态代码:
class CRMContactsAdd(CreateView):
def form_invalid(self, form):
response = super().form_invalid(form)
response.status_code = 400
return response