python - Django forms.VaildationError 未显示在基于类的 View 上

标签 python django

我的 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/

相关文章:

python - 使用 Python 在 Raspberry Pi USB 端口上使用 uart

python - 如何解决python上的安装错误

python - 在 python 中创建非阻塞套接字

python - Django 导入日期时间

python - 通过 m2m 关系的直通表的值过滤 django 查询集

Python3 看不到 Django

python - 在python中声明和填充二维数组

python - 如何在 Python 中临时修改 sys.path?

python - 自定义字段的 to_python 不工作? - Django

python - 使用 Python social auth 只获取 token