#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2010 Étienne Loks # Copyright (C) 2007 skam # (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 . # 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'''

''' % { 'attrs' : flatatt(final_attrs), 'js' : self.render_js(final_attrs['id']), }