Added extra_info field to Book model.
[wolnelektury.git] / apps / catalogue / fields.py
1 # -*- coding: utf-8 -*-
2 import datetime
3
4 from django.conf import settings
5 from django.db import models
6 from django.db.models import signals
7 from django.dispatch import dispatcher
8 from django import forms
9 from django.forms.widgets import flatatt
10 from django.forms.util import smart_unicode
11 from django.utils import simplejson as json
12 from django.utils.html import escape
13 from django.utils.safestring import mark_safe
14
15
16 class JSONEncoder(json.JSONEncoder):
17     def default(self, obj):
18         if isinstance(obj, datetime.datetime):
19             return obj.strftime('%Y-%m-%d %H:%M:%S')
20         elif isinstance(obj, datetime.date):
21             return obj.strftime('%Y-%m-%d')
22         elif isinstance(obj, datetime.time):
23             return obj.strftime('%H:%M:%S')
24         return json.JSONEncoder.default(self, obj)
25
26
27 def dumps(data):
28     return JSONEncoder().encode(data)
29
30
31 def loads(str):
32     return json.loads(str, encoding=settings.DEFAULT_CHARSET)
33
34
35 class JSONField(models.TextField):
36     def db_type(self):
37         return 'text'
38     
39     def get_internal_type(self):
40         return 'TextField'
41
42     def pre_save(self, model_instance, add):
43         value = getattr(model_instance, self.attname, None)
44         return dumps(value)
45
46     def contribute_to_class(self, cls, name):
47         super(JSONField, self).contribute_to_class(cls, name)
48         signals.post_init.connect(self.post_init, sender=cls)
49
50         def get_json(model_instance):
51             return dumps(getattr(model_instance, self.attname, None))
52         setattr(cls, 'get_%s_json' % self.name, get_json)
53
54         def set_json(model_instance, json):
55             return setattr(model_instance, self.attname, loads(json))
56         setattr(cls, 'set_%s_json' % self.name, set_json)
57
58     def post_init(self, **kwargs):
59         instance = kwargs.get('instance', None)
60         value = self.value_from_object(instance)
61         if (value):
62             setattr(instance, self.attname, loads(value))
63         else:
64             setattr(instance, self.attname, None)
65
66
67 class JQueryAutoCompleteWidget(forms.TextInput):
68     def __init__(self, source, options=None, *args, **kwargs):
69         self.source = source
70         self.options = None
71         if options:
72             self.options = dumps(options)
73         super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
74     
75     def render_js(self, field_id):
76         source = "'%s'" % escape(self.source)
77         options = ''
78         if self.options:
79             options += ', %s' % self.options
80         
81         return u'$(\'#%s\').autocomplete(%s%s);' % (field_id, source, options)
82     
83     def render(self, name, value=None, attrs=None):
84         final_attrs = self.build_attrs(attrs, name=name)
85         if value:
86             final_attrs['value'] = smart_unicode(value)
87         
88         if not self.attrs.has_key('id'):
89             final_attrs['id'] = 'id_%s' % name
90         
91         html = u'''<input type="text" %(attrs)s/>
92             <script type="text/javascript">//<!--
93             %(js)s//--></script>
94             ''' % {
95                 'attrs' : flatatt(final_attrs),
96                 'js' : self.render_js(final_attrs['id']),
97             }
98         
99         return mark_safe(html)
100
101
102 class JQueryAutoCompleteField(forms.CharField):
103     def __init__(self, source, options=None, *args, **kwargs):
104         if 'widget' not in kwargs:
105             kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
106         
107         super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
108