我在我的 中创建了一个clean_message
方法forms.py
,它检查是否self.message
有东西,并在没有的情况下引发 a 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,)))