1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django import forms
5 from django.forms.utils import flatatt
6 from django.utils.encoding import smart_str
7 from django.utils.safestring import mark_safe
11 class JQueryAutoCompleteWidget(forms.TextInput):
12 def __init__(self, options, *args, **kwargs):
13 self.options = dumps(options)
14 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
16 def render_js(self, field_id, options):
17 return '$(\'#%s\').autocomplete(%s).result(autocomplete_result_handler);' % (field_id, options)
19 def render(self, name, value=None, attrs=None, renderer=None):
20 final_attrs = self.build_attrs(self.attrs, attrs)
21 final_attrs["name"] = name
23 final_attrs['value'] = smart_str(value)
25 if 'id' not in self.attrs:
26 final_attrs['id'] = 'id_%s' % name
28 html = '''<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=None, *args, **kwargs):
51 if 'widget' not in kwargs:
52 options['source'] = source
53 kwargs['widget'] = JQueryAutoCompleteWidget(options)
55 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
58 class JQueryAutoCompleteSearchField(forms.CharField):
59 def __init__(self, options=None, *args, **kwargs):
62 if 'widget' not in kwargs:
63 kwargs['widget'] = JQueryAutoCompleteSearchWidget(options)
65 super(JQueryAutoCompleteSearchField, self).__init__(*args, **kwargs)