更改元素的类属性-Django表单
我有登记表,我正在使用Django登记。现在,我需要向每个字段添加css类。另外,如果有验证错误,那么css类对于有错误的字段应该是不同的。我怎样才能做到这一点更改元素的类属性-Django表单,django,django-templates,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
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>
您可以将表单字段作为目标,而无需向每个字段添加类。只需使用类似于以下内容的CSS规则,具体取决于您是使用
作为表
(表单unicode方法的默认值)、作为表
还是作为表
form tr {...}
form li {...}
form p {...}
对于必填字段和有错误的字段,可以分别为表单定义required\u css\u class
和error\u css\u class
属性
class ContactForm(Form):
error_css_class = 'error'
required_css_class = 'required'
有关更多信息,请参阅的文档
如果手动呈现模板中的表单字段,则可以使用该方法访问该字段的css类
*电邮地址:
{{form.email}
+1。人们似乎忘记了级联样式表的级联部分。我添加了这两个属性,但它不起作用。字段的定义类似于email=forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)),label=(“email address”))如果它不起作用,请使用您的表单、模板和您获得的输出更新您的问题。啊,您正在模板中手工呈现字段。在这种情况下,可以使用绑定字段的css\u class
方法。我用一个例子更新了我的答案。
class ContactForm(Form):
error_css_class = 'error'
required_css_class = 'required'
<div class="row {{ form.email.css_classes }}">
<label for="id_email"><span>*</span> Email Address:</label>
{{ form.email }}
</div>