2016-03-20 36 views
0

只能找到舊的答案和例子,我不明白在視圖中顯示錯誤。顯示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}}等,但沒有奏效。我猜想我正在重新加載表單,因此消息不顯示。

+0

有{{form.errors}}。我想Django文檔在解釋這個時很清楚。 –

回答

0

要在表單級別顯示錯誤,您可以簡單地使用:{{ form.errors }}。但似乎你想要現場級別的錯誤信息。對於這一點,你需要修改的清潔方法,因爲這樣:

def clean_message(self): 
    if not self.message: 
     raise ValidationError({'message': ['You must enter your comment']) 

這樣,錯誤將適當field.errors進行設置。

+0

我錯過了什麼嗎?我已經完成了你所說的,但根本沒有消息。也許放一個'else',以防表單無效? – mfgabriel92

+0

@GabrielMFernandes你如何顯示錯誤?你使用'form.errors'嗎?或者'field.errors'? –

+0

我用過'form.errors'。我從哪裏得到'field'?根據另一個例子,現在我已將'clean_comment'移到'forms.py'。 – mfgabriel92