为什么我看不到来自 ValidationError Django 的错误消息?

Why I cannot see a error message from ValidationError Django?

我已经完成了 Django 文档中写的内容,并且尝试了几个 Youtube 教程,包括 Whosebug 的建议。但是,我无法使消息“验证错误”出现在模板上。当我单击按钮创建一个带有 bad_word 的 post 时,我重定向到同一页面,post 没有保存,但表单没有向我显示消息。我试图在视图中保存打印( 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: