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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.