2014-02-11 18 views
1

我想將一個自定義表單錯誤賦值給django中的模型表單中的某個字段,以便它出現「標準」錯誤(如字段留空) ,具有相同的格式(由脆皮形式處理)。在django中爲模型表單中的字段賦值自定義表單錯誤

我的模型形式的清潔方法是這樣的:

def clean(self): 
    cleaned_data = super(CreatorForm, self).clean() 
    try: 
     if cleaned_data['email'] != cleaned_data['re_email']: 
      raise forms.ValidationError({'email': "Your emails don't match!"}) 
    except KeyError: 
     pass 
    return cleaned_data 

而且在我的模板我顯示窗體/重新提交的表單是這樣的:

{{creator_form|crispy}} 

我希望錯誤出現如果可能的話,在re_email字段下面(儘管目前我認爲我會在電子郵件字段下方獲得更好的運氣),此時它出現在表單頂部,未格式化。 0對於re_email字段,儘管不屬於模型的一部分,但顯示的將其留空的錯誤顯示在re_email字段下。如何將錯誤附加到字段,以便它們顯示在下方/附近?

所有幫助表示讚賞感謝

回答

3

爲了得到錯誤,顯示你需要明確定義錯誤中有哪些領域上,因爲你要覆蓋.clean()特定的字段。以下是取自Django docs的一個樣本:

class ContactForm(forms.Form): 
    # Everything as before. 
    ... 

    def clean(self): 
     cleaned_data = super(ContactForm, self).clean() 
     cc_myself = cleaned_data.get("cc_myself") 
     subject = cleaned_data.get("subject") 

     if cc_myself and subject and "help" not in subject: 
      # We know these are not in self._errors now (see discussion 
      # below). 
      msg = u"Must put 'help' in subject when cc'ing yourself." 
      self._errors["cc_myself"] = self.error_class([msg]) 
      self._errors["subject"] = self.error_class([msg]) 

      # These fields are no longer valid. Remove them from the 
      # cleaned data. 
      del cleaned_data["cc_myself"] 
      del cleaned_data["subject"] 

     # Always return the full collection of cleaned data. 
     return cleaned_data 
+0

很酷,謝謝scott – holmeswatson

相關問題