See docstring
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | # $Id: ReadOnlyWidget.py 487 2009-08-12 09:01:09Z tguettler $
# $HeadURL: svn+ssh://svnserver/svn/djangotools/trunk/widgets/ReadOnlyWidget.py $
# This is http://www.djangosnippets.org/snippets/1682/
# based on http://www.djangosnippets.org/snippets/937/
from django import forms
from django.db import models
empty_magic=object()
class ReadOnlyWidget(forms.Widget):
u'''
Usage1: foo_field.widget=ReadOnlyWidget(mystring)
Usage2: ReadOnlyWidget(myint, my_display_string)
Usage3: ReadOnylWidget(form=myform, field_name='foo')
'''
def __init__(self, original_value=empty_magic, display_value=None, form=None, name=None):
if original_value is empty_magic:
assert form and name
field=form.fields[name]
original_value = form.initial.get(name, field.initial)
if callable(original_value):
original_value = original_value()
if isinstance(field, forms.ChoiceField):
for v, display in field.choices:
if v==original_value:
display_value=display
break
else:
assert not (form or name)
if display_value is None:
if original_value is None:
display_value=u''
else:
display_value=original_value
if isinstance(original_value, models.Model):
original_value=original_value.pk
self.original_value = original_value
self.display_value = display_value
super(ReadOnlyWidget, self).__init__()
def render(self, name, value, attrs=None):
if self.display_value is not None:
if not isinstance(self.display_value, basestring):
return unicode(self.display_value)
return self.display_value
return unicode(self.original_value)
def value_from_datadict(self, data, files, name):
return self.original_value
|
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
what does this do: empty_magic=object()
?
#
wait, I read the code now. ok
#
Please login first before commenting.