eedff6705b0d7dcc6b13b6c1bdce7fed9fdac6d0
[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 JSONFormField(forms.CharField):
35     widget = forms.Textarea
36     
37     def clean(self, value):
38         try:
39             loads(value)
40             return value
41         except ValueError, e:
42             raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
43
44
45 class JSONField(models.TextField):
46     def formfield(self, **kwargs):
47         defaults = {'form_class': JSONFormField}
48         defaults.update(kwargs)
49         return super(JSONField, self).formfield(**defaults)
50
51     def db_type(self):
52         return 'text'
53
54     def get_internal_type(self):
55         return 'TextField'
56
57     def contribute_to_class(self, cls, name):
58         super(JSONField, self).contribute_to_class(cls, name)
59         
60         def get_value(model_instance):
61             return loads(getattr(model_instance, self.attname, None))
62         setattr(cls, 'get_%s_value' % self.name, get_value)
63
64         def set_value(model_instance, json):
65             return setattr(model_instance, self.attname, dumps(json))
66         setattr(cls, 'set_%s_value' % self.name, set_value)
67
68
69 class JQueryAutoCompleteWidget(forms.TextInput):
70     def __init__(self, source, options=None, *args, **kwargs):
71         self.source = source
72         self.options = None
73         if options:
74             self.options = dumps(options)
75         super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
76     
77     def render_js(self, field_id):
78         source = "'%s'" % escape(self.source)
79         options = ''
80         if self.options:
81             options += ', %s' % self.options
82         
83         return u'$(\'#%s\').autocomplete(%s%s);' % (field_id, source, options)
84     
85     def render(self, name, value=None, attrs=None):
86         final_attrs = self.build_attrs(attrs, name=name)
87         if value:
88             final_attrs['value'] = smart_unicode(value)
89         
90         if not self.attrs.has_key('id'):
91             final_attrs['id'] = 'id_%s' % name
92         
93         html = u'''<input type="text" %(attrs)s/>
94             <script type="text/javascript">//<!--
95             %(js)s//--></script>
96             ''' % {
97                 'attrs' : flatatt(final_attrs),
98                 'js' : self.render_js(final_attrs['id']),
99             }
100         
101         return mark_safe(html)
102
103
104 class JQueryAutoCompleteField(forms.CharField):
105     def __init__(self, source, options=None, *args, **kwargs):
106         if 'widget' not in kwargs:
107             kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
108         
109         super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
110