2011-04-29 21 views
0

在168頁中,有兩段代碼:實用Django的項目 - 頁168

def clean_password2(self): 
    if self.cleaned_data['password1'] != self.cleaned_data['password2']: 
     raise forms.ValidationError("You must type the same password each time") 
    return self.cleaned_data['password2'] 

def clean(self): 
    if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: 
     if self.cleaned_data['password1'] != self.cleaned_data['password2']: 
     raise forms.ValidationError("You must type the same password each time") 
    return self.cleaned_data 

在第二種情況下,代碼檢查「密碼1」和「密碼2」是否有任何價值。在第一種情況下,沒有這種檢查。爲什麼?

回答

1

clean_password2您正在驗證password2字段,因此您可以確定它存在於該表單中,並且不需要檢查self.cleaned_data中是否存在該字段。但這並不意味着他們也不能檢查password1的情況。

clean方法正在驗證整個表單並且不能保證存在的內容。

+0

非常感謝你們倆。我正在尋找一個允許用戶只有在被邀請才能訂閱的代碼(有點像Quora)。我在哪裏可以找到?謝謝。 – Peter 2011-04-29 23:04:32

1

clean_password2方法正在對字段進行清理,在這種情況下是password2字段。 (docs

clean方法在個別字段驗證後調用。根據文檔,這是進行多場驗證的好地方。

瞭解更多here

+0

這是一個:-) – Fitoria 2011-04-29 22:42:17