我是Django和python的新手,正在努力從書中學習它。在下面的代碼中,我試圖確保password1和password2是相同的,但它似乎不運行clean_password2驗證,因爲即使它們具有不同的值,它始終返回true。Django form.is_valid總是返回true
import re
from django.contrib.auth.models import User
from django import forms
class RegistrationForm(forms.Form):
username = forms.CharField(label=u'Username', max_length=30)
email = forms.EmailField(label=u'Email')
password1 = forms.CharField(
label= u'Password',
widget = forms.PasswordInput()
)
password2 = forms.CharField(
label= u'Password (Again)',
widget = forms.PasswordInput()
)
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 != password2:
raise forms.ValidationError('Passwords do not match.')
return password2
要在多個字段(正是這種用例)上執行驗證,您應該重寫Form的'clean()'方法。例如,請參閱http://docs.djangoproject.com/en/1.3/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other。 – dcrosta 2011-05-03 21:39:51