Login

ReadOnlyWidget

Author:
guettli
Posted:
August 13, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

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

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

#

Please login first before commenting.