2010-03-14 88 views
1

任何機構都可以告訴我如何比較django中的兩個字段。 因爲我在我的forms.py文件中有兩個密碼字段。 現在我想比較兩個字段,如果兩者都相同,則將用戶保存在數據庫 中否則會附加錯誤消息以再次輸入值。比較django中的兩個字段

感謝

+3

http://docs.djangoproject.com/zh/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other – 2010-03-14 23:50:02

+0

http://pypi.python。組織/的PyPI/django的登記/ 0.7 – 2010-03-14 23:53:32

回答

2

重寫表單的clean方法:

class MyRegistrationForm(forms.Form): 
    password1=... 
    password2=... 
    ... 

def clean(self): 
    cleaned_data = self.cleaned_data # individual field's clean methods have already been called 
    password1 = cleaned_data.get("password1") 
    password2 = cleaned_data.get("password2") 
    if password1 != password2: 
     raise forms.ValidationError("Passwords must be identical.") 

    return cleaned_data 

更多信息,請參見the docs

您應該也可能會添加一些Javascript來檢查這在客戶端 - 客戶端驗證不是服務器端驗證的替代品,但它更響應用戶,並節省帶寬。