【发布时间】: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