Django 验证不起作用,仅防止空格

Django Validation not working, prevent whitespace only

提问人:Zursen 提问时间:8/8/2023 更新时间:8/8/2023 访问量:29

问:

所以我正在使用 Django 创建一个博客项目。用户可以对博客文章发表评论、编辑和删除等。如果用户尝试输入空注释,我想提供错误。如果评论只包含空格,或者他们可能点击提交按钮而没有任何评论。

在我的 forms.py 中,我按照 django 文档添加了 clean_body 函数。他们还提到在我包含的模板中使用“{{ form.non_field_errors }}”。“表单”是否需要替换为 forms.py 中的表单名称?

现在,当我加载博客文章时,评论字段会立即显示“此字段为必填项”,如果我添加带有空格的评论,页面将刷新并显示相同的“此字段为必填项”,而不是我添加的唯一错误消息。

最后补充一点,我把'from django.core.exceptions import ValidationError'放在我的 forms.py 文件中。

[HTML全

<div class="card-body">
                {% if user.is_authenticated %}

                <h3>Leave a comment:</h3>
                <p>Posting as: {{ user.username }}</p>
                <form id="commentForm" method="post" style="margin-top: 1.3em;">
                    {{ comment_form | crispy }}
                    {{ form.non_field_errors }}
                    {% csrf_token %}
                    <button id="submitButton" type="submit" class="btn btn-primary primary-color btn-lg">Submit</button>
                </form>
                {% else %}
                <h3>Log in or Register to leave a comment.</h3>
                {% endif %}

Forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('body',)

    def clean_body(self):
        cleaned_data = super(CommentForm, self).clean()
        body = cleaned_data.get("body")
        if body.isspace():
            raise forms.ValidationError("Your comment was blank, please enter a comment")  # noqa
        return cleaned_data

Views.py

def post_detail(request, slug, *arghs, **kwargs):
    queryset = Post.objects.filter(status=1)
    post = get_object_or_404(queryset, slug=slug)
    comments = post.comments.all().order_by('created_on')
    comment_count = post.comments.filter(approved=True).count()
    liked = False
    commented = False

    if post.likes.filter(id=request.user.id).exists():
        liked = True

    comment_form = CommentForm()  # Initialize unbound form first

    if request.method == "POST" and request.user.is_authenticated:
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            comment_form.instance.email = request.user.email
            comment_form.instance.name = request.user.username
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.save()
            messages.add_message(request, messages.SUCCESS, 'Comment awaiting moderation')  # noqa

    return render(
        request,
        "post_detail.html",
        {
            "post": post,
            "comments": comments,
            "comment_count": comment_count,
            "liked": liked,
            "comment_form": comment_form
        }
    )

Models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE,
                             related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    approved = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return f"Comment {self.body} by {self.name}"
Django 验证

评论

0赞 willeM_ Van Onsem 8/8/2023
通常,该字段已经从文本中剥离了数据,因此它将是空的,而不是空格。
0赞 Zursen 8/8/2023
@WillemVanOnsem 现在,当我加载博客文章时,它会立即显示“此字段为必填项”,即使用户甚至没有尝试提交。有没有办法修复我的代码,使其仅在单击提交按钮后显示此消息?
0赞 Ahtisham 8/9/2023
@Zursen 在模板中删除non_field_errors

答: 暂无答案