2013-05-07 56 views
2

我有一個基本的註冊表單,其中包括一個BooleanField供人們接受條款和隱私政策。我想要做的是改變如果用戶沒有檢查出現的ValidationError的語言。在Django表單上產生自定義驗證錯誤的問題

class RegisterForm(forms.Form): 
    username = forms.CharField(label="Username") 
    email = forms.EmailField(label="Email") 
    location = forms.CharField(label="Location",required=False) 
    headline = forms.CharField(label="Headline",required=False) 
    password = forms.CharField(widget=forms.PasswordInput,label="Password") 
    confirm_password = forms.CharField(widget=forms.PasswordInput,label="Confirm Password") 
    terms = TermsField(label=mark_safe("I have read and understand the <a href='/terms'>Terms of Service</a> and <a href='/privacy'>Privacy Policy</a>."),required=True) 

TermsFieldBooleanField子類:

class TermsField(forms.BooleanField): 
    "Check that user agreed, return custom message." 

    def validate(self,value): 
     if not value: 
      raise forms.ValidationError('You must agree to the Terms of Service and Privacy Policy to use this site.') 
     else:  
      super(TermsField, self).validate(value) 

它正確地驗證中,如果用戶不檢查他們TermsField形式不驗證,但它返回通用的「這是必須填寫」錯誤。這似乎是一個非常簡單的任務,我確信我正在做一些基本錯誤的事情。有任何想法嗎?

回答

4

這是因爲Django認爲該字段是必需的,並且沒有提供任何值,所以它甚至不會打擾調用您的validate方法(這是在內置驗證之後發生的)。

的方式來完成你要完成的是:

class RegisterForm(forms.Form): 
    # ...other fields 
    terms = forms.BooleanField(
     required=True, 
     label=mark_safe('I have read and understand the <a href=\'/terms\'>Terms of Service</a> and <a href=\'/privacy\'>Privacy Policy</a>.') 
     error_messages={'required': 'You must agree to the Terms of Service and Privacy Policy to use Prospr.me.'} 
    ) 

這將覆蓋Field.default_error_messages定義默認的「要求」消息。