Login

Dojo Helper

Author:
limscoder
Posted:
April 27, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

This module contains functions and classes that help integrate the Dojo Toolkit javascript library with Django. Supports defining theme, stylesheets, required modules, and addOnLoad functions from Django. Django form fields can be instrumented to be instantiated as Dijit form objects programmatically.

Full instructions on limscoder.com.

  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
224
225
226
227
228
229
230
"""Integrates Dojo with Django."""

import json
import uuid

# Used to convert Django Field attributes to Dojo attributes.
#
# Key is Django Field attribute name.
# Value is tuple.
# [0] == Dijit attribute name
# [1] == callable to convert Django value to Dijit value
default_attr_map = {
    'required': ('required', None),
    'min_length': ('minLength', None),
    'max_length': ('maxLength', None),
    'regex': ('regExp', lambda a: a.pattern)
}

def dojo_field(field, dojo_type, attr_map=None, dojo_attrs=None):
    """
    Instruments a Django form.Field with Dijit parameters.

    arguments
    ==========
    * field - Django form.Field to instrument.
    * dojo_type - str, qualified class name of dijit class to use.
    * attr_map - dict, optional mapping between Django and Dojo
                 attrs, see default_attr_map comments for format.
    * dojo_attrs - dict, Attributes to apply to Dijit.
    """

    # Specifies mapping between Django field attributes
    # and Dijit attributes
    if attr_map is not None:
        map = dict(default_attr_map)
        map.update(attr_map)
    else:
        map = default_attr_map

    # Get mapped attributes from Django field
    attrs = {}
    for attr, mapper in map.iteritems():
        val = getattr(field, attr, None)
        if val is None:
            continue

        if mapper[1] is not None:
            val = mapper[1](val)

        attrs[mapper[0]] = val

    # Convert Error message
    error_msgs = getattr(field, 'error_messages', None)
    if error_msgs is not None:
        invalid_msg = error_msgs.get('invalid', None)
        if invalid_msg is not None:
            # Django uses a
            # lazy proxy when this property is not
            # explicitly set. json encoder will choke
            # on the proxy object. Calling a method 
            # causes the proxy to be evaluated and
            # json encoder is happy.
            attrs['invalidMessage'] = invalid_msg.rstrip()

    # Add user defined attributes
    if dojo_attrs is not None:
        attrs.update(dojo_attrs)

    # Attach Dojo attributes to field
    field._dojo_type = dojo_type
    field._dojo_params = attrs

class Dojo(object):
    """Keeps track of Dojo properties."""

    def __init__(self, src, enabled=True, theme='tundra',
                 dj_config=None, form_function=None):
        self.enabled = enabled
        self.dj_config = dj_config
        self.form_function = form_function

        self._src = src
        self._stylesheets = ['/'.join((self._src, 'dojo', 'resources', 'dojo.css'))]
        self._modules = [] #required_modules
        self._aols = [] # addOnLoad functions
        self.theme = theme

    def get_src(self):
        return self._src
    src = property(get_src)

    def get_theme(self):
        return self._theme

    def set_theme(self, val):
        def _get_theme_css(theme):
            return '/'.join((self._src, 'dijit', 'themes',
                             theme, '%s.css' % theme))

        current_theme = getattr(self, '_theme', None)
        if current_theme is not None:
            theme_css = _get_theme_css(current_theme)
            if theme_css in self._stylesheets:
                self._stylesheets.remove(theme_css)

        self._theme = val
        theme_css = _get_theme_css(self._theme)
        self.append_stylesheet(theme_css)
    theme = property(get_theme, set_theme)

    def get_modules(self):
        return self._modules

    def set_modules(self, val):
        self._modules = val
    modules = property(get_modules, set_modules)

    def get_stylesheets(self):
        return self._stylesheets

    def set_stylesheets(self, val):
        self._stylesheets = val
    stylesheets = property(get_stylesheets, set_stylesheets)

    def get_aols(self):
        return self._aols

    def set_aols(self, val):
        self._aols = val
    aols = property(get_aols, set_aols)

    def set_module_path(self, module, path):
        """Short cut for setting module path in djConfig."""

        if 'modulePaths' not in self.dj_config:
            self.dj_config['modulePaths'] = {}
        self.dj_config['modulePaths'][module] = path

    def append_module(self, module):
        """Add a required module."""

        if module not in self._modules:
            self._modules.append(module)

    def append_stylesheet(self, stylesheet):
        """Add a stylesheet."""

        if stylesheet not in self._stylesheets:
            self._stylesheets.append(stylesheet)

    def append_aol(self, aol):
        """Add an addOnLoad function."""

        self._aols.append(aol)

    def prepend_aol(self, aol):
        self._aols.insert(0, aol)

    def dojo_form(self, form, form_function=None):
        """
        Generates Javascript to instrument a Dijit form.

        Adds an addOnLoad handler that instantiates a
        Dijit form when the page loads.

        Any fields that have been setup with dojo_field
        will also be instantiated as Dijits.

        """

        dijits = []
        for bound_field in form:
            field = bound_field.field
            dojo_type = getattr(field, '_dojo_type', None)
            if dojo_type is not None:
                # This is a dojo enabled widget
                params = getattr(field, '_dojo_params', {})
                params['dojoType'] = dojo_type
                self.append_module(dojo_type)
                dijits.append({'name': bound_field.name, 'params': params})

        json_dijits = json.dumps(dijits)

        self.append_module('dijit.form.Form')

        if getattr(form, 'id', None) is None:
            # Form must have a unique id for
            # JS form instrumentation to work
            # correctly.
            form.id = str(uuid.uuid1())

        if form_function is None:
            # Form function wasn't passed,
            # use form_function member var instead
            form_function = self.form_function

        if form_function is None:
            # Generate JS
            self.append_module('dojo.parser')
            self.append_aol(self._build_form_js(form.id, json_dijits))
        else:
            # Call existing JS function
            self.append_module(form_function[0])
            function_name = '.'.join(form_function)
            function_call = "function() {%s('%s', %s);}" % (function_name, form.id, json_dijits)
            self.append_aol(function_call)

    def _build_form_js(self, form_id, json_dijits):
        """Builds a JS function string used to dijitize a form."""

        return """
function () {
    var dijitForm = dojo.byId('%(form_id)s');
    if (dijitForm != null) {
        var elements = [];
        var dijits = %(json_dijits)s;
        dojo.forEach(dijits, function(dijit) {
            var n = dijitForm.elements[dijit.name];
            if (n != null) {
                dojo.attr(n, dijit.params);
                elements.push(n);
            }
        });

        dojo.attr(dijitForm, {dojoType: 'dijit.form.Form'}); 
        elements.push(dijitForm);
        dojo.parser.instantiate(elements);
    }
}
""" % {'form_id': form_id, 'json_dijits': json_dijits}

More like this

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

Comments

Please login first before commenting.