Reputation: 335
I am rendering my form using
{{ form.as_p }}
in my templates.
But I would like to have some of the "p" added some classes (not all of them), so I can have some sort of grouping between my fields thanks to css.
How would you do that?
Thank you!
Upvotes: 1
Views: 2916
Reputation: 11561
Specify the widget and initialize it with the class you need. Like so:
name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
Django documunation is here: http://docs.djangoproject.com/en/1.3/ref/forms/widgets/#django.forms.Widget.attrs
Edit:
Forms are best structured with fieldsets. Unfortunately django currently doesn't 'support' them. The current state is best summarized here: Django and fieldsets on ModelForm
Upvotes: 2
Reputation: 599956
If you want anything even remotely beyond what Django gives you with as_p
, you should specify the fields yourself. You'll get much more control without having to hack around. A simple template tag like display_field will allow you just to specify each field, its label and errors with a single tag. Then you can group the fields yourself using the HTML element meant for that: a fieldset.
<fieldset class="my_fieldset">
{% display_field form.field1 %}
{% display_field form.field2 %}
</fieldset>
Upvotes: 2
Reputation: 18982
Check this question for some ideas: Django Forms Template design classes
You could probably combine the suggested approach with the :nth-child-selector to match the paragraphs you want.
Depending on the complexity of your form i would consider to render the form manually though.
Upvotes: 0