Login

DefaultValueWidget

Author:
miracle2k
Posted:
July 17, 2007
Language:
Python
Version:
.96
Tags:
newforms forms widgets widget
Score:
5 (after 5 ratings)

Can be used if a form field should not be editable, but the current value or the value that will be automatically used should still be visible to the user.

init takes two additional parameters: value is the actual value to be used when saving the form, while display determines what is shown to the user when rendering. If display is not specified, value itself will be used instead.

If display is a ModelChoiceField, value is assumed to be a primary key of the model, and the widget will automatically try to retrieve and use the string representation of the corresponding item.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class DefaultValueWidget(forms.widgets.Widget):
    def __init__(self, value, display=None, attrs=None):        
        if isinstance(display, forms.ModelChoiceField):
            try:
                object = display.queryset.get(pk=value)
                self.display = str(object)
            except:
                self.display = None
        # this allows to genericly pass in any field object intending to to
        # catch ModelChoiceFields, without having to care about the actual
        # type.
        elif isinstance(display, forms.Field):
            self.display = None
        else:
            self.display = display
        self.value = value
        super(DefaultValueWidget, self).__init__(attrs)    
        
    def value_from_datadict(self, data, name):
        return self.value
    
    def render(self, name, value, attrs=None):
        if self.display is None: return self.value
        else: return self.display

More like this

  1. ManyToManyField no syncdb by powerfox 6 years, 6 months ago
  2. Number generator to autofill a field by pizte 5 years, 1 month ago
  3. DisableableSelectWidget by notanumber 3 years, 3 months ago
  4. Currency Fields with newforms by sago 8 years, 3 months ago
  5. Confirm alert if the user navigates away without saving changes by mrazzari 6 years ago

Comments

Please login first before commenting.