我的 forms.validationerror 没有显示。下面是我正在使用的表格。 if 语句有效,它检测到问题,并成功打印出内容。正如 stackoverflow 上的许多现有错误所表明的那样,内容不是 print 语句中所示的 None。
class PollItemMessageAddForm(forms.ModelForm):
class Meta:
model = Message
fields = [
"content"
]
labels = {
'content': 'Add your comment',
}
widgets = {
'content': Textarea(attrs={'cols': 10, 'rows': 5}),
}
def __init__(self, *args, **kwargs):
# this line should be before a super call
self.request = kwargs.pop('request', None)
super(PollItemMessageAddForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', value='Post', css_class='buttonspace btn-success'))
def clean_content(self):
content = self.cleaned_data.get("content")
if len(content) > 50:
print content
raise forms.ValidationError("Please limit your message to less the 50 characters")
return content
下面是我的基于类的 View 中的views.py post语句,它跳过form.isvalid以重定向到应出现错误消息的同一url。如果有帮助的话,我正在基于类的 View 中使用详细 View 和 formmixin。在没有回溯的情况下,我看不出问题来自哪里。任何帮助将不胜感激。
def post(self, request, *args, **kwargs):
url = "/polls/" + str(self.get_object().id)
form = self.get_form()
if request.method == "POST":
if form.is_valid():
print "works"
return self.form_valid(form)
return HttpResponseRedirect(url)
最佳答案
如果表单无效,您必须像这样返回:
return render(request, self.template_name, {'errors': form.errors, 'form':form})
并在模板中显示错误,或者在模板内的{{ form.non_field_errors }}
将显示错误。
关于python - Django forms.VaildationError 未显示在基于类的 View 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47648632/