Login

MultiSelect checkbox iterator template filter

Author:
ke1g
Posted:
August 16, 2010
Language:
Python
Version:
1.0
Tags:
Score:
3 (after 3 ratings)

Sometimes you want more rendering control than common widgets give you. We wrote this, for example, to allow rendering the checkboxes of a multi select field with checkbox widget, as multiple columns.

Place this in the templatetags subdirectory of an app you are loading (be sure it has a init.py file), and load it something like this (you may want to shorten the name):

{% load checkboxiterator_filter %}

Then you can say something like:

{% for checkbox in form.categories|checkboxiterator %} {# other code #}{{ checkbox }}{# other code #} {% endfor %}

where form.categories is a multiple select field (no doubt this technique could be applied to radio buttons and a single select field).

The filter does use some internal interfaces, but may well still work on newer Django version.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# Copyright (C) 2010 Appropriate Solutions, Inc., all rights reserved.
# This code is released to be used under the terms of the Apache license, by
# Bill Freeman, for Appropriate Solutions, Inc., www.appropriatesolutions.com

from django import template
from django.utils.html import conditional_escape
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
import django.forms

# NOTE: This code takes advantage of django internal interfaces.
# Such are subject to change in new django versions, making this
# code invalid.  It was developed and tested for a Django 1.0.3
# (pinax) based site.  I make no presentation that this stuff
# will work on any other version, or even this version with a
# different set of apps or versions.  But it should be close.
# Your milage may vary.

register = template.Library()

class _PseudoCheckboxBoundField(object):
    """An object from which to render one checkbox.

    Helper class.

    Because the checkbox iterator needs to be able return something
    that acts, closely enough, like a checkbox bound field.
    """
    def __init__(self, name, option_label, option_value, attrs, checked):
        self.parent_name = name
        self.name = option_label
        self.value = option_value
        self.attrs = attrs
        self.checked = checked
        self.id = attrs.get('id', '')
        self.errors = u'' # We don't have individual cb errors

    def tag(self):
        cb = django.forms.CheckboxInput(self.attrs,
                                        check_test=lambda v: self.checked)
        return cb.render(self.parent_name, self.value)

    def label_head(self):
        id = self.id
        if not id:
            return u'<label>'
        return mark_safe(u'<label for="%s">' % id)

    def labeled(self):
        return mark_safe(u'%s%s %s</label>' % (
            self.label_head(),
            self.tag(),
            self.name
            ))

    def lone_label(self):
        return mark_safe(u'%s%s</label>' % (
            self.label_head(),
            self.name
            ))

    def __unicode__(self):
        return self.labeled()

class _ValueGrabber(object):
    """A pseudo widget to capture information from the MultiSelect object.

    This is a helper class.

    There's no clean way to reach into the MultiSelect bound field to
    get this information, but it does call its widget with all the
    necessary info.  This probably has legs because changing the
    render interface would have far reaching consequences.
    """
    def __init__(self):
        self.attrs = {}

    def render(self, name, data, attrs):
        self.name = name
        self.data = data
        self.attrs = attrs

@register.filter
def checkboxiterator(bound_field):
    """Filter the bound field of a multi-select into an iterator of checkboxes.

    Passing the multiselect into the filter gives us access to the bound
    field here.

    We then actually behave as a generator of _PseudoCheckboxBoundField
    objects, which is iterable.
    """
    widget = bound_field.field.widget
    # Snag the bound field details.  Let it's as_widget method do the work.
    bfd = _ValueGrabber()
    bound_field.as_widget(bfd)
    name = bfd.name
    values = bfd.data
    attrs = bfd.attrs

    # Fix up data and attrs
    if values is None:
        values = set()
    else:
        values = set([force_unicode(v) for v in values])
    id = attrs and attrs.get('id', False)
    partial_attrs = widget.build_attrs(attrs, name=name)

    for i, (option_value, option_label) in enumerate(widget.choices):
        option_value = force_unicode(option_value)
        final_attrs = partial_attrs
        if id is not False:
            final_attrs = dict(partial_attrs,
                               id=u'%s_%s' % (id, i))
        yield _PseudoCheckboxBoundField(
            name,
            conditional_escape(force_unicode(option_label)),
            option_value,
            final_attrs,
            option_value in values)

More like this

  1. Dynamically change a form select widget to a hidden widget by epicserve 6 years ago
  2. Add CSS class template filter by lazerscience 4 years, 8 months ago
  3. Safe template decorator by eternicode 3 years, 1 month ago
  4. DropDownMultiple widget by marinho 7 years, 2 months ago
  5. Multiple Select Widget with jQueryUI by maguspk 5 years ago

Comments

Lacour (on August 22, 2010):

Helped me a lot! And works also on Django 1.2.1.

#

seafangs (on October 6, 2012):

Excellent, thank you. Still working in Django 1.4.

#

Please login first before commenting.