summaryrefslogtreecommitdiff
path: root/ishtar/furnitures/widgets.py
blob: bbcb584239a5a43a355e5ec56568ba10ad58d03a (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>
# Copyright (C) 2007  skam <massimo dot scamarcia at gmail.com>
#                          (http://djangosnippets.org/snippets/233/)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.
from django import forms
from django.forms.widgets import flatatt
from django.utils.encoding import smart_unicode
from django.utils.html import escape
from django.utils.simplejson import JSONEncoder

class JQueryAutoComplete(forms.TextInput):
    def __init__(self, source, options={}, attrs={}):
        """
        Source can be a list containing the autocomplete values or a
        string containing the url used for the request.
        """
        self.options = None
        self.attrs = {}
        self.source = source
        if len(options) > 0:
            self.options = JSONEncoder().encode(options)
        self.attrs.update(attrs)

    def render_js(self, field_id):
        if isinstance(self.source, list):
            source = JSONEncoder().encode(self.source)
        elif isinstance(self.source, str) or isinstance(self.source, unicode):
            source = "'%s'" % escape(self.source)
        else:
            try:
                source = "'" + unicode(self.source) +"'"
            except:
                raise ValueError('source type is not valid')
        options = 'source : ' + source
        options += ''', select: function( event, ui ) {
            $("#result").html(ui.item ?
                    "Selected: " + ui.item.value + " aka " + ui.item.id :
                    "Nothing selected, input was " + this.value );
        },minLength: 2

        '''
        if self.options:
            options += ',%s' % self.options

        return u'$(\'#%s\').autocomplete({%s});' % (field_id, options)

    def render(self, name, value=None, attrs=None):
        final_attrs = self.build_attrs(attrs, name=name)
        if value:
            final_attrs['value'] = escape(smart_unicode(value))

        if not self.attrs.has_key('id'):
            final_attrs['id'] = 'id_%s' % name
        return u'''<input %(attrs)s/><p id="result"></p>
        <script type="text/javascript"><!--//
        $(function() {%(js)s});//--></script>
        ''' % {
            'attrs' : flatatt(final_attrs),
            'js' : self.render_js(final_attrs['id']),
        }