Added short_html method to Book model and removed (no longer used) book template...
[wolnelektury.git] / catalogue / fields.py
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
8
9
10 class JQueryAutoCompleteWidget(forms.TextInput):
11     def __init__(self, source, options=None, *args, **kwargs):
12         self.source = source
13         self.options = None
14         if options:
15             self.options = dumps(options)
16         super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
17     
18     def render_js(self, field_id):
19         source = "'%s'" % escape(self.source)
20         options = ''
21         if self.options:
22             options += ', %s' % self.options
23         
24         return u'$(\'#%s\').autocomplete(%s%s);' % (field_id, source, options)
25     
26     def render(self, name, value=None, attrs=None):
27         final_attrs = self.build_attrs(attrs, name=name)
28         if value:
29             final_attrs['value'] = smart_unicode(value)
30         
31         if not self.attrs.has_key('id'):
32             final_attrs['id'] = 'id_%s' % name
33         
34         html = u'''<input type="text" %(attrs)s/>
35             <script type="text/javascript"><!--//
36             %(js)s//--></script>
37             ''' % {
38                 'attrs' : flatatt(final_attrs),
39                 'js' : self.render_js(final_attrs['id']),
40             }
41         
42         return mark_safe(html)
43
44
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)
49         
50         super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
51