【问题标题】:Django ifequal not workingDjango ifequal 不工作
【发布时间】:2014-02-03 07:55:38
【问题描述】:

这是我的注册表:

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 字段返回错误。我确实在RegistrationForm中说过

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

但是 Django 直接进入 else 语句,并且当它执行该行时

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

当我检查网络浏览器时,它说

Password (Again) : This field is required.

所以

field.label_tag

等于

"Password (Again)"

对吗?我的怎么来的

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

语句的评估结果不正确?

【问题讨论】:

    标签: django django-forms django-authentication django-templates django-errors


    【解决方案1】:

    您在浏览器中看到的并不是field.label_tag 的真实样子。

    其实field.label_tag是这样的(可以看HTML源码):

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

    引用一位伟人(和 Django documentation)的话:

    {{ field.label_tag }} 字段的标签包裹在适当的 HTML 标记。

    这段代码应该可以工作:

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

    现在,显然没有人愿意编写这样的代码。带有 HTML 代码的字符串?来吧,奈杰尔,你比这更好!

    这是更好的方法:

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

    实际上,我认为还有更好的方法来处理表单错误。您可以阅读文档here

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 2011-01-07
      • 2012-07-28
      • 2017-12-29
      • 2010-10-01
      • 2011-11-22
      • 2013-11-29
      • 2012-02-23
      • 1970-01-01
      相关资源
      最近更新 更多