【问题标题】:How to display alert errors in Django如何在 Django 中显示警报错误
【发布时间】:2016-03-20 23:50:25
【问题描述】:

我在我的forms.py 中创建了一个clean_message 方法,用于检查self.message 是否有东西,如果没有,则引发ValidationError

"""
Comment
"""
class CommentForm(forms.Form):
    """
    Comment field
    """
    comment = forms.CharField(
        widget = forms.Textarea(
            attrs = {
                'class': 'form-control',
                'rows': 2 
            }
        )
    )

    def clean_comment(self):
        if self.cleaned_data['comment'] is None:
            raise form.ValidationError({'comment': ['You must enter your comment'])

这是视图文件。我需要什么来显示错误,如上所示?

<form action="comment" method="POST">
    {% csrf_token %}
    <div class="form-group">
        {{ form.comment.errors }}
        {{ form.comment }}
    </div>
    <div class="form-group">
        <input type="submit" value="Say it" class="btn btn-success"> 
    </div>
</form>

我尝试使用{{ form.errors }},对其进行迭代,使用{{ form.non_field_errors }} 等,但都没有成功。我想我正在重新加载表单,因此没有显示消息。

下面是我的write_comment方法,点击按钮发表评论时执行的方法:

def write_comment(request, post_id):
    """
    Write a new comment to a post
    """
    form = CommentForm(request.POST or None)

    if form.is_valid():
        post = Post.objects.get(pk = post_id)
        post.n_comments += 1
        post.save()

        comment = Comment()
        comment.comment = request.POST['comment']
        comment.created_at = timezone.now()
        comment.modified_at = timezone.now()
        comment.post_id = post_id
        comment.user_id = 2
        comment.save()
    else:
        form = CommentForm()

    return redirect(reverse('blog:post', args = (post_id,)))

【问题讨论】:

  • 我会仔细检查您的表单action。您确定要发布到正确的 URL 吗?另一方面,没有理由进行这种验证。将required 属性设置为该字段将为您解决这个问题。
  • 我已经放置了required 并删除了clean_comment 方法。我在某处读过,为了显示错误,不能重新加载表单,我认为这正是正在发生的事情,但我不知道如何解决它。到目前为止我尝试过的所有方法都不起作用。
  • 视图至少存在两个问题。首先,通过在else 语句中设置form = CommentForm(),您将用空表单替换无效表单(有错误)。其次,您应该呈现一个包含表单的模板。您正在重定向。
  • @Alasdair 我明白了。我这样做是因为在评论后我想返回到之前的同一页面,因为它有参数,我想我不能简单地重定向到特定的模板,因为参数。
  • 重定向到原始页面并仍然显示错误很棘手。您可以使用messages framework 手动创建错误消息。另一种选择是使用来自原始页面的 ajax 请求,并使用 JavaScript 显示错误。这两种方法都比标准 Django 方法更复杂,标准 Django 方法是返回一个包含无效表单的渲染模板。

标签: django forms validationerror


【解决方案1】:

如果您希望该字段为必填项,只需使用required=True

comment = CharField(
    required=True,
    widget = forms.Textarea(
        attrs = {
            'class': 'form-control',
            'rows': 2 
        }
    )
)

这样就不用写clean_comment方法了。您当前的方法失败了,因为self.cleaned_data['comment'] 是空字符串'',但只有None 才会显示错误。

在模板中,{{ form.comment.errors }} 应该可以正常工作。

【讨论】:

  • 我认为当验证失败时我做错了什么。该页面似乎正在刷新并隐藏任何错误消息。它仍然不起作用,@Alasdair。
  • 我不确定“刷新和隐藏错误消息是什么意思”。你的观点可能有问题,但你没有表现出来,所以我们无法判断。
  • 我更新了我的问题,添加了负责撰写新评论的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
相关资源
最近更新 更多