search fix
[wolnelektury.git] / src / search / fields.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from django import forms
5 from django.forms.utils import flatatt
6 from django.forms.widgets import RadioSelect
7 from django.utils.encoding import smart_str
8 from django.utils.safestring import mark_safe
9 from json import dumps
10
11
12 class JQueryAutoCompleteWidget(forms.TextInput):
13     def __init__(self, options, *args, **kwargs):
14         self.options = dumps(options)
15         super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
16
17     def render_js(self, field_id, options):
18         return '$(\'#%s\').autocomplete(%s).result(autocomplete_result_handler);' % (field_id, options)
19
20     def render(self, name, value=None, attrs=None, renderer=None):
21         final_attrs = self.build_attrs(self.attrs, attrs)
22         final_attrs["name"] = name
23         if value:
24             final_attrs['value'] = smart_str(value)
25
26         if 'id' not in self.attrs:
27             final_attrs['id'] = 'id_%s' % name
28
29         html = '''<input type="text" %(attrs)s/>
30             <script type="text/javascript">//<!--
31             %(js)s//--></script>
32             ''' % {
33                 'attrs': flatatt(final_attrs),
34                 'js': self.render_js(final_attrs['id'], self.options),
35             }
36
37         return mark_safe(html)
38
39
40 class JQueryAutoCompleteSearchWidget(JQueryAutoCompleteWidget):
41     def __init__(self, *args, **kwargs):
42         super(JQueryAutoCompleteSearchWidget, self).__init__(*args, **kwargs)
43
44     def render_js(self, field_id, options):
45         return ""
46
47
48 class JQueryAutoCompleteField(forms.CharField):
49     def __init__(self, source, options=None, *args, **kwargs):
50         if options is None:
51             options = {}
52         if 'widget' not in kwargs:
53             options['source'] = source
54             kwargs['widget'] = JQueryAutoCompleteWidget(options)
55
56         super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
57
58
59 class JQueryAutoCompleteSearchField(forms.CharField):
60     def __init__(self, options=None, *args, **kwargs):
61         if options is None:
62             options = {}
63         if 'widget' not in kwargs:
64             kwargs['widget'] = JQueryAutoCompleteSearchWidget(options)
65
66         super(JQueryAutoCompleteSearchField, self).__init__(*args, **kwargs)
67
68
69
70 class InlineRadioWidget(RadioSelect):
71     option_template_name = 'search/inline_radio_widget_option.html'