Login

Django newforms ExtJS JSON Encoder

Author:
davidblewett
Posted:
June 10, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

This is a subclass of Django's built-in JSONEncoder that adds the ability to output form and field objects as ExtJS-compatible config objects.

Simple example: from django.utils import simplejson json = { 'data': [], 'success': True, 'metaData': { 'fields': SFY09RDOForm(), 'root': 'data', 'successProperty': 'success' }, } return HttpResponse(simplejson.dumps(json, cls=ExtJSONEncoder))

Where SFY09RDOForm is a subclass of django.forms.Form.

6/20/2008: Updated to pass on the help_text parameter (useful in combination with this override in ext: http://extjs.com/forum/showthread.php?t=36642)

  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
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
from copy import copy, deepcopy
from django import newforms as forms
from django.core.serializers.json import DjangoJSONEncoder
from django.newforms import fields
from django.newforms.models import QuerySetIterator, ModelChoiceField, ModelMultipleChoiceField
from signet.canvas.fields import BooleanField, NullField

class ExtJSONEncoder(DjangoJSONEncoder):
    """
    JSONEncoder subclass that knows how to encode django forms into ExtJS config objects.
    """

    CHECKBOX_EDITOR = {
        'editor': {
            'xtype': 'checkbox'
        }
    }
    COMBO_EDITOR = {
        'editor': {
            #'listWidth': 'auto',
            'width': 150,
            'xtype': 'jsoncombo'
        }
    }
    DATE_EDITOR = {
        'editor': {
            'xtype': 'datefield'
        }
    }
    EMAIL_EDITOR = {
        'vtype':'email',
        'editor': {
            'xtype': 'textfield'
        }
    }
    NUMBER_EDITOR = {
        'editor': {
            'xtype': 'numberfield'
        }
    }
    NULL_EDITOR = {
        'fieldHidden': True,
        'editor': {
            'xtype': 'textfield'
        },
    }
    TEXT_EDITOR = {
        'editor': {
            'xtype': 'textfield'
        }
    }
    TIME_EDITOR = {
        'editor': {
            'xtype': 'timefield'
        }
    }
    URL_EDITOR = {
        'vtype':'url',
        'editor': {
            'xtype': 'textfield'
        }
    }
    CHAR_PIXEL_WIDTH = 8

    EXT_DEFAULT_CONFIG = {
        'editor': TEXT_EDITOR
        #'labelWidth': 300,
        #'autoWidth': True,
    }

    DJANGO_EXT_FIELD_TYPES = {
        fields.BooleanField: ["Ext.form.Checkbox", CHECKBOX_EDITOR],
        fields.CharField: ["Ext.form.TextField", TEXT_EDITOR],
        fields.ChoiceField: ["Ext.form.ComboBox", COMBO_EDITOR],
        fields.DateField: ["Ext.form.DateField", DATE_EDITOR],
        fields.DateTimeField: ["Ext.form.DateField", DATE_EDITOR],
        fields.DecimalField: ["Ext.form.NumberField", NUMBER_EDITOR],
        fields.EmailField: ["Ext.form.TextField", EMAIL_EDITOR],
        fields.IntegerField: ["Ext.form.NumberField", NUMBER_EDITOR],
        ModelChoiceField: ["Ext.form.ComboBox", COMBO_EDITOR],
        ModelMultipleChoiceField: ["Ext.form.ComboBox", COMBO_EDITOR],
        fields.MultipleChoiceField: ["Ext.form.ComboBox",COMBO_EDITOR],
        NullField: ["Ext.form.TextField", NULL_EDITOR],
        fields.NullBooleanField: ["Ext.form.Checkbox", CHECKBOX_EDITOR],
        BooleanField: ["Ext.form.Checkbox", CHECKBOX_EDITOR],
        fields.SplitDateTimeField: ["Ext.form.DateField", DATE_EDITOR],
        fields.TimeField: ["Ext.form.DateField", TIME_EDITOR],
        fields.URLField: ["Ext.form.TextField", URL_EDITOR],
    }

    EXT_DATE_ALT_FORMATS = 'm/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d'

    EXT_TIME_ALT_FORMATS = 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d'

    DJANGO_EXT_FIELD_ATTRS = {
        #Key: django field attribute name
        #Value: tuple[0] = ext field attribute name,
        #       tuple[1] = default value
        'choices': ['store', None],
        #'default': ['value', None],
        'fieldset': ['fieldSet', None],
        'help_text': ['helpText', None],
        'initial': ['value', None],
        #'input_formats': ['altFormats', None],
        'label': ['fieldLabel', None],
        'max_length': ['maxLength', None],
        'max_value': ['maxValue', None],
        'min_value': ['minValue', None],
        'name': ['name', None],
        'required': ['allowBlank', False],
        'size': ['width', None],
        'hidden': ['fieldHidden', False],
    }

    def default(self, o):
        if issubclass(o.__class__, forms.Form):
            flds = []

            for name, field in o.fields.items():
                if isinstance(field, dict):
                    field['title'] = name
                else:
                    field.name = name
                cfg = self.default(field)
                flds.append(cfg)

            flds.append({
                "header": "text",
                "editor": {"width": 144,
                            "allowBlank": True,
                            "fieldHidden": True,
                            "xtype": "textfield",
                            "maxLength": 255},
                'name': 'text'
            })
            return flds
        elif isinstance(o, dict):
            #Fieldset
            default_config = {
                'autoHeight': True,
                'collapsible': True,
                'items': [],
                'labelWidth': 200,
                'title': o['title'],
                'xtype':'fieldset',
            }
            del o['title']

            #Ensure fields are added sorted by position
            for name, field in sorted(o.items()):
                field.name = name
                default_config['items'].append(self.default(field))
            return default_config
        elif issubclass(o.__class__, fields.Field):
            default_config = {}
            if o.__class__ in self.DJANGO_EXT_FIELD_TYPES:
                default_config.update(self.DJANGO_EXT_FIELD_TYPES[o.__class__][1])
            else:
                default_config.update(self.EXT_DEFAULT_CONFIG['editor'])
            config = deepcopy(default_config)
            for dj, ext in self.DJANGO_EXT_FIELD_ATTRS.items():
                v = None
                if dj == 'size':
                    v = o.widget.attrs.get(dj, None)
                    if v is not None:
                        if o.__class__ in (fields.DateField, fields.DateTimeField,
                           fields.SplitDateTimeField, fields.TimeField):
                            v += 8
                        #Django's size attribute is the number of characters,
                        #so multiply by the pixel width of a character
                        v = v * self.CHAR_PIXEL_WIDTH
                elif dj == 'hidden':
                    v = o.widget.attrs.get(dj, default_config.get('fieldHidden', ext[1]))
                elif dj == 'name':
                    v = o.name
                elif getattr(o, dj, ext[1]) is None:
                    pass
                #elif dj == 'input_formats':
                    #alt_fmts = []
                    ##Strip out the '%'  placeholders
                    #for fmt in getattr(field, dj, ext[1]):
                        #alt_fmts.append(fmt.replace('%', ''))
                    #v = u'|'.join(alt_fmts)
                elif isinstance(ext[1], basestring):
                    v = getattr(o, dj, getattr(field, ext[1]))
                elif ext[0] == 'store':
                    v = {
                        'autoLoad': True,
                        'storeId': o.name,
                        'url': '/csds/ext/rdo/queryset/%s/' % (o.name.lower(),),
                        #'xtype': 'jsonstore',
                    }
                else:
                    v = getattr(o, dj, ext[1])
                if v is not None:
                    if ext[0] == 'value':
                        config[ext[0]] = v
                    if ext[0] == 'name':
                        config[ext[0]] = v
                        config['header'] = v
                    elif ext[0] not in ('name', 'dataIndex', 'fieldLabel', 'header', 'defaultValue'):
                    #elif ext[0] in ('allowBlank', 'listWidth', 'store', 'width'):
                            #if isinstance(v, QuerySetIterator):
                            #    config['editor'][ext[0]] = list(v)
                        config[ext[0]] = v
                        config['editor'][ext[0]] = v
                        if ext[0] == 'store':
                            config['url'] = v['url']
                            config['editor']['displayField'] = 'display'
                            #config['editor']['forceSelection'] = True
                            config['editor']['hiddenName'] = o.name
                            config['editor']['lastQuery'] = ''
                            config['editor']['mode'] = 'remote'
                            config['editor']['triggerAction'] = 'all'
                            config['editor']['valueField'] = 'id'

                    elif isinstance(v, unicode):
                        config[ext[0]] = v.encode('utf8')
                    else:
                        config[ext[0]] = v
            return config
        else:
            return super(ExtJSONEncoder, self).default(o)

More like this

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

Comments

peter (on June 12, 2008):

that is I need, thanks

#

Huuuze (on July 2, 2008):

I'm new to Django. Can you provide a simple example on how to integrate this into a ModelForm?

#

antmangaka (on March 16, 2009):

Hello, thanks for the code, can you provide a working example? Thank you!

#

Please login first before commenting.