I have registration form and I am using Django-registration. Now, I need to add css class to each field. Also, if there are validation errors, then css class should be different for the fields which have error. How can I achieve this?
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)"))
In html template, I am doing
<div class="row">
<label for="id_email"><span>*</span> Email Address:</label>
{{ form.email }}
</div>
Note Eventually, I ended up using widget_tweaks, which allowed me to do
{{form.email|add_class:"blink"|add_error_class:"error"}}
You can target form fields without adding a class to each field. Just use CSS rules similar to the following, depending on whether you are rendering the form using
as_table(the default for the form’s unicode method),as_uloras_p.For required fields and fields with errors, you can define
required_css_classanderror_css_classattributes respectively for a form.For more information see the docs for Styling required or erroneous form rows.
If you manually render the form fields in your template, you can access the field’s css classes using the
css_classesmethod.