1

I have some code that looks like:

  #form.html
  <form action="/form-action" method="post">
    {{form.faction.label_tag}}
    {{form.faction}}<br />
    {{form.character_name.label_tag}}
    {{form.character_name}}
  </form>

  #form.py
  class CharacterForm(forms.Form):
    FACTION_CHOICES = (
      ('Sith', 'Sith Empire'),
      ('Republic', 'Republic Alliance')
    )
    faction = forms.ChoiceField(choices=FACTION_CHOICES)
    character_name = forms.CharField(max_length=100)

However I would like have a specified class on the label tag on the html output. I know I could do:

  <form action="/form-action" method="post">
    <label for="id_faction" class="foo">{{form.faction.label}}:</label>
    {{form.faction}}<br />
    <label for="id_character_name" class="bar">{{form.character_name.label}}:</label>
    {{form.character_name}}
  </form>

I previously used Rails and you can do something along the lines of:

<%= f.label :field, class: "baz"  %>

and was hoping there was just as easy of a solution in django. I thought using form.field-name.label_tag(attrs={'class':'custom-class-name'}) was going to work out but alas I am stuck. Any insight is appreciated.

Erik
  • 898
  • 2
  • 8
  • 28
  • Have a look at: http://stackoverflow.com/questions/6959178/how-to-set-css-class-of-a-label-in-a-django-form-declaration for some ideas. – Brandon Taylor Oct 08 '14 at 16:27
  • maybe this will help: http://stackoverflow.com/questions/414679/add-class-to-django-label-tag-output – Sasa Oct 08 '14 at 16:28
  • 1
    On another note please try to port your application to a newer Django if possible as 1.5 is [now considered insecure](https://docs.djangoproject.com/en/1.5/). – cms_mgr Oct 08 '14 at 16:39
  • It's possible to add a class to the actual input via: 'character_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'foo'}))' But nothing like that for labels. – Erik Oct 08 '14 at 18:29

1 Answers1

0

For this i always use widget_tweaks

  1. Install it : pip install django-widget-tweaks .
  2. Add 'widget_tweaks' to INSTALLED_APPS in settings.py after django apps and just before your apps.
  3. Add {% load widget_tweaks %} to the top of the template you will customise.

Now to add a class for a field "name" of form1 do :

{{ form1.name|add_class:"baz" }}

or add 2 and more

{{ form1.name|add_class:"baz baz2 baz3" }}

which will add class ="baz baz2 baz3" to your field html output

You can also add attributes :

{{ form1.name|attr:"size:200"|attr:"color:blue"}}

and combine the two ^^

{{ form1.name|add_class:"baz baz2 baz3"|attr:"size:200"|attr:"color:blue"}}

You can also test field type for an adapted output by including snippets according to type. it's what i do. Go consult the docs of widget_tweaks it works for me on Django 1.6 and 1.7 Hope it will help you

Cherif KAOUA
  • 834
  • 12
  • 21
  • I'll have to take a look into this, but hopefully a non-third party solution reveals itself. – Erik Oct 08 '14 at 19:11