Add class to specific fields in django forms
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!
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>
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
Create custom template tag to render the form as you want.
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.
精彩评论