source: asadb/util/db_form_utils.py @ b928edc

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

Make StaticWidget? work with Select fields too

  • Property mode set to 100644
File size: 1.8 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        return self.value
29
30    def render(self, name, value, attrs=None, choices=(), ):
31        if value is None:
32            value = ''
33        label = value
34        the_choices = chain(self.choices, choices)
35        for choice_value, choice_label in the_choices:
36            if choice_value == value:
37                label = choice_label
38        # We have this inner hidden widget because that allows us to nicely
39        # handle a transition from StaticWidget to another widget type
40        # (e.g., the user loads a form while unauthenticated and submits while
41        # authenticated)
42        hidden_render = self.inner.render(name, value, attrs=attrs)
43        return mark_safe(conditional_escape(label) + hidden_render)
44
45    @classmethod
46    def replace_widget(cls, formfield, value):
47        choices = None
48        choices = getattr(formfield.widget, 'choices', ())
49        formfield.widget = cls(value=value, choices=choices)
Note: See TracBrowser for help on using the repository browser.