これは私の登録フォームです:
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(label='Password', widget=forms.PasswordInput())
password2 = forms.CharField(label='Password (Again)', widget=forms.PasswordInput())
def clean_password2(self):
if 'password1' in self.cleaned_data:
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
username = self.cleaned_data['username']
if not re.search(r'^\w+$', username): #checks if all the characters in username are in the regex. If they aren't, it returns None
raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.')
try:
User.objects.get(username=username) #this raises an ObjectDoesNotExist exception if it doesn't find a user with that username
except ObjectDoesNotExist:
return username #if username doesn't exist, this is good. We can create the username
raise forms.ValidationError('Username is already taken.')
これは私のテンプレートです:
{% if form.errors %}
{% for field in form %}
{% if field.label_tag == "Password (Again)" %}
<p>The passwords which you entered did not match.</p>
{% else %}
{{ field.label_tag }} : {{ field.errors }}
{% endif %}
{% endfor %}
{% endif %}
基本的に言いたい
The passwords which you entered did not match.
Django が password2 フィールドのエラーを返した場合。私は登録フォームでそれを言いました
password2 = forms.CharField(label='Password (Again)'
しかし、Djangoはelseステートメントに直接進み、行を実行すると
{{ field.label_tag }} : {{ field.errors }}
Webブラウザを確認すると、
Password (Again) : This field is required.
そう
field.label_tag
等しい
"Password (Again)"
右?どうして私の
if field.label_tag == "Password (Again)"
ステートメントが true と評価されていませんか?