1 | from django.forms.widgets import Widget, Select, HiddenInput |
---|
2 | from django.utils.safestring import mark_safe |
---|
3 | from django.utils.html import conditional_escape |
---|
4 | from itertools import chain |
---|
5 | |
---|
6 | class 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) |
---|