【问题标题】:Why I cannot see a error message from ValidationError Django?为什么我看不到来自 ValidationError Django 的错误消息?
【发布时间】:2021-08-28 13:54:32
【问题描述】:

我已经完成了 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>

【问题讨论】:

    标签: django validationerror


    【解决方案1】:

    如果您的表单无效,您总是会在没有表单信息的情况下重定向到“/”。您的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:
    

    【讨论】:

      猜你喜欢
      • 2012-11-06
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 2020-04-22
      相关资源
      最近更新 更多