ReadOnlyWidget

 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

  1. . by jeremydw 3 years, 8 months ago
  2. madslug by catellar 2 years, 7 months ago
  3. watermark by dingdongquan 3 years, 3 months ago
  4. convert youtube url for iframe, js api by ivanff 1 year ago
  5. default url routing and shortcut by vicalloy 4 years, 10 months ago

Comments

anentropic (on October 20, 2009):

what does this do: empty_magic=object()

?

#

anentropic (on October 20, 2009):

wait, I read the code now. ok

#

(Forgotten your password?)