1 # -*- coding: utf-8 -*-
2 from django import forms
3 from django.forms.widgets import flatatt
4 from django.forms.util import smart_unicode
5 from django.utils.html import escape
6 from django.utils.safestring import mark_safe
7 from django.utils.simplejson import dumps
10 class JQueryAutoCompleteWidget(forms.TextInput):
11 def __init__(self, source, options=None, *args, **kwargs):
15 self.options = dumps(options)
16 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
18 def render_js(self, field_id):
19 source = "'%s'" % escape(self.source)
22 options += ', %s' % self.options
24 return u'$(\'#%s\').autocomplete(%s%s);' % (field_id, source, options)
26 def render(self, name, value=None, attrs=None):
27 final_attrs = self.build_attrs(attrs, name=name)
29 final_attrs['value'] = smart_unicode(value)
31 if not self.attrs.has_key('id'):
32 final_attrs['id'] = 'id_%s' % name
34 html = u'''<input type="text" %(attrs)s/>
35 <script type="text/javascript"><!--//
38 'attrs' : flatatt(final_attrs),
39 'js' : self.render_js(final_attrs['id']),
42 return mark_safe(html)
45 class JQueryAutoCompleteField(forms.CharField):
46 def __init__(self, source, options=None, *args, **kwargs):
47 if 'widget' not in kwargs:
48 kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
50 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)