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