Django Forms framework is excellent and renders the entire form by just the following.
{{ form.as_p }}
For a registration form, it converts
If you just need all labels to have a particular class, the best way would be to change the markup and CSS slightly. Put a <div>
with your class around the form:
<div class="field-title">
{{ form.as_p }}
</div>
and make the CSS definition as follows:
div.field-title label {
...
}
Here's a similar question: Add class to Django label_tag() output . I'm not sure if the chosen answer to that one will fit your needs or not.
I was also searching for the same, just adding the info if you are not aware of this.
If you want to apply css to specific field, you can extract the individual form fields as like follows
Eg: form field name
:
{{ form.name.label }}
{{ form.name.errors }}
{{ form.name }}
{{ form.name.help_text }}
Now, instead of {{ form.name.label }}
, you can provide your own formatting as you mentioned.
Another way is adding the classname through javascript.
Adding the class directly to the Form Field as Attribute, seemed the DRY'est way for me.
name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"}))
message = forms.CharField(widget=forms.Textarea(attrs={"class":"form-control bar foo"}))
This way you don't need to edit anything anywhere else. You can add as many classes to specific fields this way as you want.