This is my registration form:

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.')

and this is my template:

{% 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 %}

I basically want to say

The passwords which you entered did not match.

if Django returns an error for the password2 field. I did say in the RegistrationForm that

password2 = forms.CharField(label='Password (Again)'

but Django goes straight to the else statement and when it executes the line

{{ field.label_tag }} : {{ field.errors }}

and when I check the web browser, it says

Password (Again) : This field is required.

So

field.label_tag

does equal

"Password (Again)"

right? How come my

if field.label_tag == "Password (Again)"

statement is not evaluating to true?

有帮助吗?

解决方案

What you see in the browser is not what field.label_tag really is.

Actually field.label_tag is something like this (you can look at the HTML source):

<label for="id_password2">Password (Again):</label>

To quote a great man (and Django documentation):

{{ field.label_tag }} The field’s label wrapped in the appropriate HTML tag.

This code should work:

{% if field.label_tag == '<label for="id_password2">Password (Again):</label>' %}
etc

Now, obviously, nobody wants to write code like this. Strings with the HTML code? Come on, Nigel, you're better than this!

Here is the better way:

{% if field.name == 'password2' %}
etc

Actually, I think there is even a better way to handle form errors. You can read the documentation here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top