[英]django class based generic view “CreateView” unique slug error handeling
So I have a CreateView and it works 99% the way I want. 所以我有一个CreateView,它可以按我希望的方式工作99%。 If a user enters a letter in an integer field it tells the user to enter a number, if a user leaves a required field blank it tells them that they need to fill it in. This is all great, CreateView handles the errors for me. 如果用户在整数字段中输入字母,则会告诉用户输入数字,如果用户将必填字段保留为空白,则会告诉用户需要填写。这很不错,CreateView会为我处理错误。 However, for obvious reasons, I am not letting the user create the slug field, this is created automatically by taking the date and two other fields combining them and slugifying them. 但是,出于明显的原因,我不允许用户创建slug字段,这是通过将日期和另外两个字段结合起来并对其进行分段处理而自动创建的。 If the user attempts to create a record that wouldn't result in a unique slug then the form is invalid but CreateView doesn't give any constructive feedback (unless you are in debug mode, then you get UNIQUE constraint failed). 如果用户尝试创建不会导致唯一记录的记录,则该表单无效,但CreateView不会提供任何建设性反馈(除非您处于调试模式,否则UNIQUE约束将失败)。
If I add the code below to my CreateView, then I need to re-define all the error responses that CreateView was handling so nicely before. 如果我将以下代码添加到我的CreateView中,那么我需要重新定义CreateView之前处理得很好的所有错误响应。
def form_invalid(self, form):
return HttpResponse(#define stuff here)
Is there a way I can have CreateView handle invalid forms normally (as if I didn't have def form_invalid(self, form):
) except for when there is a slug conflict? 除了发生a冲突之外,是否有办法让CreateView正常处理无效表单(好像我没有def form_invalid(self, form):
?
You can do that by calling the parent's class version of form_invalid
inside your overriding of form_invalid
. 您可以通过在覆盖form_invalid
内部调用父类的form_invalid
的类版本来form_invalid
。
Example: 例:
class MyCreateView(CreateView):
def form_invalid(self, form):
if my_condition: # Check whatever you want
return HttpResponse('reason it failed')
else: # Or call the parent class version
return super(MyCreateView, self).form_invalid(form)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.