2011-10-30 212 views
29

我有一個非常簡單的形式:自定義表單驗證

from django import forms 

class InitialSignupForm(forms.Form): 
    email = forms.EmailField() 
    password = forms.CharField(max_length=255, widget = forms.PasswordInput) 
    password_repeat = forms.CharField(max_length=255, widget = forms.PasswordInput) 

    def clean_message(self): 
     email = self.clean_data.get('email', '') 
     password = self.clean_data.get('password', '') 
     password_repeat = self.clean_data.get('password_repeat', '') 

     try: 
      User.objects.get(email_address = email) 
      raise forms.ValidationError("Email taken.") 
     except User.DoesNotExist: 
      pass 

     if password != password_repeat: 
      raise forms.ValidationError("The passwords don't match.") 

請問這是怎麼自定義窗體驗證呢?我需要評估email目前沒有用戶使用該電子郵件地址。我還需要評估passwordpassword_repeat的匹配。我怎麼能這樣做呢?

+0

我寧願就mothel而不是形式的檢驗:http://beutil.blogspot.com/2011/10/django-moving- business-rules-from-views.html – danihp

回答

83

要驗證它自己的一個字段,你可以在你的形式使用clean_FIELDNAME()方法,因此對於電子郵件:

def clean_email(self): 
    email = self.cleaned_data['email'] 
    if User.objects.filter(email=email).exists(): 
     raise ValidationError("Email already exists") 
    return email 

則依賴於彼此相互依存的字段,可以覆蓋形式這是所有字段後運行(如上面emailclean()方法進行了驗證個別:

def clean(self): 
    form_data = self.cleaned_data 
    if form_data['password'] != form_data['password_repeat']: 
     self._errors["password"] = ["Password do not match"] # Will raise a error message 
     del form_data['password'] 
    return form_data 

我不知道你在哪裏得到了clean_message(),但看起來是做了一個驗證方法一個 message字段似乎不存在於您的表單中。

有通過此瞭解更多詳情閱讀:

https://docs.djangoproject.com/en/dev/ref/forms/validation/

+4

只是一個小的通知......'form_data ['password']!= form_data ['password']'可能應該有'password2'這樣的密碼重複字段。 – andi

+0

雅..應該是:form_data ['password']!= form_data ['password_repeat'] – pavanw3b

+0

我已經更改爲'password_repeat',謝謝! –