为什么我看不到来自 ValidationError Django 的错误消息? view.pyforms.py模板终端打印

问题描述

我已经完成了 Django 文档中所写的内容,并且我尝试了几个 Youtube 教程,包括 Stackoverflow 的建议。但是,我无法在模板上显示“验证错误”消息。当我单击按钮创建带有 bad_word 的帖子时,我重定向到同一页面,帖子未保存,但表单未向我显示消息。我试图在视图中保存一个打印( form.errors ),终端显示了我想在模板中看到的消息。所以我不知道我做错了什么...

view.py

if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        title = form.cleaned_data['title']
        content = form.cleaned_data['content']
        username = User.objects.get(username=f"{request.user}")
        new_post = Post(user=username,title=title,content=content,datetime=timezone.Now())
        new_post.writeOnChain()
        cache.expire("cache",timeout=0)
    return HttpResponseRedirect("/")
else:
    form = PostForm()
return render(request,"api/homepage.html",{'form': form,'postList': postList})

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title','content',)

    def clean_title(self):
        title = self.cleaned_data['title']
        if "bad_word" in title:
            raise forms.ValidationError("Error")
        return title

    def clean_content(self):
        content = self.cleaned_data['content']
        if "bad_word" in content:
            raise forms.ValidationError("Error")
        return content

模板

<div class="p-3 forms m-3">
    <form class="crispy" action="{% url 'homepage' %}" method="post">
         {% csrf_token %}
         {{ form|crispy }}
        <input type="submit" class="btn buttons" value="Create Post">
    </form>
</div>

终端打印

<ul class="errorlist"><li>content<ul> class="errorlist"><li>Error</li></ul> </li></ul>

解决方法

如果您的表单无效,您总是重定向到没有表单信息的“/”。您的 return redirect 需要与“有效”表单代码的其余部分缩进。

if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        title = form.cleaned_data['title']
        content = form.cleaned_data['content']
        username = User.objects.get(username=f"{request.user}")
        new_post = Post(user=username,title=title,content=content,datetime=timezone.now())
        new_post.writeOnChain()
        cache.expire("cache",timeout=0)
        return HttpResponseRedirect("/") # this line here
else:

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...