只能找到舊的答案和例子,我不明白在視圖中顯示錯誤。顯示ValidationError被提出的每個字段的驗證錯誤
我創建了一個我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}}等,但沒有奏效。我猜想我正在重新加載表單,因此消息不顯示。
有{{form.errors}}。我想Django文檔在解釋這個時很清楚。 –