Multiple-Submit-Button Widget for Choice Field

 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
# -*- coding: utf-8 -*-
from django import forms
from django.utils.safestring import mark_safe

class SubmitButton(forms.Widget):
    """
    A widget that handles a submit button.
    """
    def __init__(self, name, value, label, attrs):
        self.name, self.value, self.label = name, value, label
        self.attrs = attrs
        
    def __unicode__(self):
        final_attrs = self.build_attrs(
            self.attrs,
            type="submit",
            name=self.name,
            value=self.value,
            )
        return mark_safe(u'<button%s>%s</button>' % (
            forms.widgets.flatatt(final_attrs),
            self.label,
            ))

class MultipleSubmitButton(forms.Select):
    """
    A widget that handles a list of submit buttons.
    """
    def __init__(self, attrs={}, choices=()):
        self.attrs = attrs
        self.choices = choices

    def __iter__(self):
        for value, label in self.choices:
            yield SubmitButton(self.name, value, label, self.attrs.copy())

    def __unicode__(self):
        return '<button type="submit" />'
        
    def render(self, name, value, attrs=None, choices=()):
        """Outputs a <ul> for this set of submit buttons."""
        self.name = name
        return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join(
            [u'<li>%s</li>' % force_unicode(w) for w in self],
            ))
    def value_from_datadict(self, data, files, name):
        """
        returns the value of the widget: IE posts inner HTML of the button
        instead of the value.
        """
        value = data.get(name, None)
        if value in dict(self.choices):
            return value
        else:
            inside_out_choices = dict([(v, k) for (k, v) in self.choices])
            if value in inside_out_choices:
                return inside_out_choices[value]
        return None

More like this

  1. Radio widget with labels after inputs by avsd 1 year, 9 months ago
  2. load m2m fields objects by dirol 3 years, 10 months ago
  3. Model field choices as a namedtuple by whiteinge 3 years ago
  4. CheckboxMultiSelect with interable checkboxes by pyramids16 1 year, 5 months ago
  5. simple jquery example by lawgon 5 years, 12 months ago

Comments

jon_elsas (on September 22, 2010):

amazingly useful drop-in replacement for a single radio-button choice form. thanks!

#

jasonyo (on April 10, 2011):

Excellent. I recommend adding the following import statement:

from django.utils.encoding import force_unicode

#

(Forgotten your password?)