fix invalid boxes for pdcounter authors
[wolnelektury.git] / src / search / fields.py
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.
4 #
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
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 u'$(\'#%s\').autocomplete(%s).result(autocomplete_result_handler);' % (field_id, options)
19
20     def render(self, name, value=None, attrs=None):
21         final_attrs = self.build_attrs(attrs, name=name)
22         if value:
23             final_attrs['value'] = smart_unicode(value)
24
25         if 'id' not in self.attrs:
26             final_attrs['id'] = 'id_%s' % name
27
28         html = u'''<input type="text" %(attrs)s/>
29             <script type="text/javascript">//<!--
30             %(js)s//--></script>
31             ''' % {
32                 'attrs': flatatt(final_attrs),
33                 'js': self.render_js(final_attrs['id'], self.options),
34             }
35
36         return mark_safe(html)
37
38
39 class JQueryAutoCompleteSearchWidget(JQueryAutoCompleteWidget):
40     def __init__(self, *args, **kwargs):
41         super(JQueryAutoCompleteSearchWidget, self).__init__(*args, **kwargs)
42
43     def render_js(self, field_id, options):
44         return u""
45
46
47 class JQueryAutoCompleteField(forms.CharField):
48     def __init__(self, source, options=None, *args, **kwargs):
49         if options is None:
50             options = {}
51         if 'widget' not in kwargs:
52             options['source'] = source
53             kwargs['widget'] = JQueryAutoCompleteWidget(options)
54
55         super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
56
57
58 class JQueryAutoCompleteSearchField(forms.CharField):
59     def __init__(self, options=None, *args, **kwargs):
60         if options is None:
61             options = {}
62         if 'widget' not in kwargs:
63             kwargs['widget'] = JQueryAutoCompleteSearchWidget(options)
64
65         super(JQueryAutoCompleteSearchField, self).__init__(*args, **kwargs)