source: asadb/util/db_form_utils.py

space-accessstablestagetest-hooks
Last change on this file was b63d6b2, checked in by Alex Dehnert <adehnert@…>, 14 years ago

Allow non-Exec to actually edit groups

The StaticWidget? would previously return the model as the value from a
foreign key field. This fails when it tries to get converted. Now, if we're
passed choices, we'll compare their labels against the unicode form of the
value, and see what matches.

Obviously, this means that your values need to unique. OTOH, (a) this is
probably a good idea, and (b) if you don't do this, your admin users, who
actually get to select a value, will have trouble selecting something
reasonable too. Consequently, I don't think I care that much.

  • Property mode set to 100644
File size: 1.9 KB
Line 
1from django.forms.widgets import Widget, Select, HiddenInput
2from django.utils.safestring import mark_safe
3from django.utils.html import conditional_escape
4from itertools import chain
5
6class StaticWidget(Widget):
7    """Widget that just displays and supplies a specific value.
8
9    Useful for "freezing" form fields --- displaying them, but not
10    allowing editing.
11    """
12
13    def __init__(self, *args, **kwargs):
14        self.value = kwargs['value']
15        del kwargs['value']
16        if 'choices' in kwargs:
17            if kwargs['choices'] is not None:
18                self.choices = kwargs['choices']
19            else:
20                self.choices = ()
21            del kwargs['choices']
22        else:
23            self.choices = ()
24        super(StaticWidget, self).__init__(*args, **kwargs)
25        self.inner = HiddenInput()
26
27    def value_from_datadict(self, data, files, name, ):
28        for choice_value, choice_label in self.choices:
29            if choice_label == unicode(self.value):
30                return choice_value
31        return self.value
32
33    def render(self, name, value, attrs=None, choices=(), ):
34        if value is None:
35            value = ''
36        label = value
37        the_choices = chain(self.choices, choices)
38        for choice_value, choice_label in the_choices:
39            if choice_value == value:
40                label = choice_label
41        # We have this inner hidden widget because that allows us to nicely
42        # handle a transition from StaticWidget to another widget type
43        # (e.g., the user loads a form while unauthenticated and submits while
44        # authenticated)
45        hidden_render = self.inner.render(name, value, attrs=attrs)
46        return mark_safe(conditional_escape(label) + hidden_render)
47
48    @classmethod
49    def replace_widget(cls, formfield, value):
50        choices = None
51        choices = getattr(formfield.widget, 'choices', ())
52        formfield.widget = cls(value=value, choices=choices)
Note: See TracBrowser for help on using the repository browser.