更改元素的类属性 - Django表单

时间:2011-12-21 12:14:16

标签: django django-templates

我有注册表,我正在使用Django注册。现在,我需要为每个字段添加css类。此外,如果存在验证错误,则css类对于有错误的字段应该是不同的。我怎样才能做到这一点?

class RegistrationForm(forms.Form):
"""
Form for registering a new user account.

Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.

Subclasses should feel free to add any additional validation they
need, but should avoid defining a ``save()`` method -- the actual
saving of collected user data is delegated to the active
registration backend.

"""
error_css_class = 'error'
required_css_class='wanted'

email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)),
                         label=_("Email address"))
password1 = forms.CharField(widget=forms.PasswordInput(render_value=False),
                            label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(render_value=False),
                            label=_("Password (again)"))

在html模板中,我正在做

<div class="row">
<label for="id_email"><span>*</span> Email Address:</label>
{{ form.email }}
</div>

注意最终,我最终使用了widget_tweaks,这让我可以做到

{{form.email|add_class:"blink"|add_error_class:"error"}}

1 个答案:

答案 0 :(得分:2)

您可以定位表单字段,而无需为每个字段添加类。只需使用类似于以下内容的CSS规则,具体取决于您是使用as_table(表单&#39; s unicode方法的默认设置),as_ul还是as_p来呈现表单。 / p>

form tr {...}
form li {...}
form p  {...}

对于包含错误的必填字段和字段,您可以分别为表单定义required_css_classerror_css_class属性。

class ContactForm(Form):
    error_css_class = 'error'
    required_css_class = 'required'

有关详细信息,请参阅Styling required or erroneous form rows的文档。

如果您在模板中手动呈现表单字段,则可以使用css_classes方法访问字段的css类。

<div class="row {{ form.email.css_classes }}">
<label for="id_email"><span>*</span> Email Address:</label>
{{ form.email }}
</div>