Login

DefaultValueWidget

Author:
miracle2k
Posted:
July 17, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.