1

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!

e-Jah
  • 335
  • 4
  • 16

4 Answers4

2

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>
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

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

Community
  • 1
  • 1
tback
  • 11,138
  • 7
  • 47
  • 71
  • The problem with this solution is that the class in only applied to the "input" tag, not to the "p" tag – e-Jah May 20 '11 at 09:19
0

Create custom template tag to render the form as you want.

DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
0

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.

Community
  • 1
  • 1
arie
  • 18,737
  • 5
  • 70
  • 76