How do I create a Django form that displays a checkbox label to the right of the checkbox?

Here’s a solution I’ve come up with (Django v1.1):

{% load myfilters %}

[...]

{% for field in form %}
    [...]
    {% if field.field.widget|is_checkbox %}
      {{ field }}{{ field.label_tag }}
    {% else %}
      {{ field.label_tag }}{{ field }}
    {% endif %}
    [...]
{% endfor %}

You’ll need to create a custom template tag (in this example in a “myfilters.py” file) containing something like this:

from django import template
from django.forms.fields import CheckboxInput

register = template.Library()

@register.filter(name="is_checkbox")
def is_checkbox(value):
    return isinstance(value, CheckboxInput)

More info on custom template tags available here.

Edit: in the spirit of asker’s own answer:

Advantages:

  1. No futzing with CSS.
  2. The markup ends up looking the way it’s supposed to.
  3. I didn’t hack Django internals. (but had to look at quite a bunch)
  4. The template is nice, compact and idiomatic.
  5. The filter code plays nice regardless of the exact values of the labels and input field names.

Disadvantages:

  1. There’s probably something somewhere out there that does it better and faster.
  2. Unlikely that the client will be willing to pay for all the time spent on this just to move the label to the right…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)