Tuesday, March 15, 2011

Add class to Django label_tag() output

I need some way to add a class attribute to the output of the label_tag() method for a forms field.

I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:

for field in form:
    print field.label_tag(attrs{'class':'Foo'})

I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?

Is there a way in my form definition to define the class to be displayed in the label?

In the form, I can do the following to give the inputs a class

self.fields['some_field'].widget.attrs['class'] = 'Foo'

I just need to have it output the class for the as well.

From stackoverflow
  • A custom template tag seems to be the solution. A custom filter would also do, although it can be less elegant. But you would need to fall back to custom form rendering in both cases.

    If this is a task of high importance; I'd create a Mixin that allows me to annotate the form fields with label classes and supplies form rendering methods using those classes. So that the following code works:

    {{ form.as_table_with_label_classes }}
    

    But I'd like to ask; Do you really need a class on the label tag? I mean HTML design-wise. It is absolutely necessary to add a class in there? Couldn't it be solved with some CSS like:

    encapsulating_selector label {
        some-attr: some-value;
    }
    

    I sometimes use jQuery for such cases where; it will improve the page if it works, but it won't be a disaster if it doesn't. And keep the HTML source as lean as possible.

  • http://www.djangosnippets.org/snippets/693/

  • http://code.google.com/p/django-html/

  • I am aggre with answer number one, with css this could be done, but. Why is the reson for this in django source.

    class BoundField(StrAndUnicode): in django.forms.forms.py that has the definition of def label_tag(self, contents=None, attrs=None): had been prepare to display this attrs in contents = u'%s' % (widget.id_for_label(id_), attrs, unicode(contents))

    but def _html_output call this function without attrs in label = bf.label_tag(label) or ''

    So I seed that django are partially prepare to this but actually it does not used that.

  • How about adding the CSS class to the form field in the forms.py, like:

    class MyForm(forms.Form):
        title = forms.CharField(widget=forms.TextInput(attrs={'class': 'foo'}))
    

    then I just do the following in the template:

    <label for="id_{{form.title.name}}" class="bar">
        {{ form.title }}
    </label>
    

    Of course this can easily be modified to work within a for loop tag in the template.

0 comments:

Post a Comment