1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from django import forms
6 from django.forms.widgets import flatatt
7 from django.utils.encoding import smart_unicode
8 from django.utils.safestring import mark_safe
12 class JQueryAutoCompleteWidget(forms.TextInput):
13 def __init__(self, options, *args, **kwargs):
14 self.options = dumps(options)
15 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
17 def render_js(self, field_id, options):
18 return u'$(\'#%s\').autocomplete(%s).result(autocomplete_result_handler);' % (field_id, options)
20 def render(self, name, value=None, attrs=None):
21 final_attrs = self.build_attrs(attrs, name=name)
23 final_attrs['value'] = smart_unicode(value)
25 if not self.attrs.has_key('id'):
26 final_attrs['id'] = 'id_%s' % name
28 html = u'''<input type="text" %(attrs)s/>
29 <script type="text/javascript">//<!--
32 'attrs': flatatt(final_attrs),
33 'js' : self.render_js(final_attrs['id'], self.options),
36 return mark_safe(html)
39 class JQueryAutoCompleteSearchWidget(JQueryAutoCompleteWidget):
40 def __init__(self, *args, **kwargs):
41 super(JQueryAutoCompleteSearchWidget, self).__init__(*args, **kwargs)
43 def render_js(self, field_id, options):
47 class JQueryAutoCompleteField(forms.CharField):
48 def __init__(self, source, options={}, *args, **kwargs):
49 if 'widget' not in kwargs:
50 options['source'] = source
51 kwargs['widget'] = JQueryAutoCompleteWidget(options)
53 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
56 class JQueryAutoCompleteSearchField(forms.CharField):
57 def __init__(self, options={}, *args, **kwargs):
58 if 'widget' not in kwargs:
59 kwargs['widget'] = JQueryAutoCompleteSearchWidget(options)
61 super(JQueryAutoCompleteSearchField, self).__init__(*args, **kwargs)