Merge branch 'master' of http://github.com/fnp/wolnelektury
[wolnelektury.git] / apps / catalogue / 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 import datetime
6
7 from django.conf import settings
8 from django.db import models
9 from django.db.models import signals
10 from django import forms
11 from django.forms.widgets import flatatt
12 from django.forms.util import smart_unicode
13 from django.utils import simplejson as json
14 from django.utils.html import escape
15 from django.utils.safestring import mark_safe
16
17
18 class JSONEncoder(json.JSONEncoder):
19     def default(self, obj):
20         if isinstance(obj, datetime.datetime):
21             return obj.strftime('%Y-%m-%d %H:%M:%S')
22         elif isinstance(obj, datetime.date):
23             return obj.strftime('%Y-%m-%d')
24         elif isinstance(obj, datetime.time):
25             return obj.strftime('%H:%M:%S')
26         return json.JSONEncoder.default(self, obj)
27
28
29 def dumps(data):
30     return JSONEncoder().encode(data)
31
32
33 def loads(str):
34     return json.loads(str, encoding=settings.DEFAULT_CHARSET)
35
36
37 class JSONFormField(forms.CharField):
38     widget = forms.Textarea
39     
40     def clean(self, value):
41         try:
42             loads(value)
43             return value
44         except ValueError, e:
45             raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
46
47
48 class JSONField(models.TextField):
49     def formfield(self, **kwargs):
50         defaults = {'form_class': JSONFormField}
51         defaults.update(kwargs)
52         return super(JSONField, self).formfield(**defaults)
53
54     def db_type(self):
55         return 'text'
56
57     def get_internal_type(self):
58         return 'TextField'
59
60     def contribute_to_class(self, cls, name):
61         super(JSONField, self).contribute_to_class(cls, name)
62         
63         def get_value(model_instance):
64             return loads(getattr(model_instance, self.attname, None))
65         setattr(cls, 'get_%s_value' % self.name, get_value)
66
67         def set_value(model_instance, json):
68             return setattr(model_instance, self.attname, dumps(json))
69         setattr(cls, 'set_%s_value' % self.name, set_value)
70
71
72 class JQueryAutoCompleteWidget(forms.TextInput):
73     def __init__(self, source, options=None, *args, **kwargs):
74         self.source = source
75         self.options = None
76         if options:
77             self.options = dumps(options)
78         super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
79     
80     def render_js(self, field_id):
81         source = "'%s'" % escape(self.source)
82         options = ''
83         if self.options:
84             options += ', %s' % self.options
85         
86         return u'$(\'#%s\').autocomplete(%s%s).result(autocomplete_result_handler);' % (field_id, source, options)
87     
88     def render(self, name, value=None, attrs=None):
89         final_attrs = self.build_attrs(attrs, name=name)
90         if value:
91             final_attrs['value'] = smart_unicode(value)
92         
93         if not self.attrs.has_key('id'):
94             final_attrs['id'] = 'id_%s' % name
95         
96         html = u'''<input type="text" %(attrs)s/>
97             <script type="text/javascript">//<!--
98             %(js)s//--></script>
99             ''' % {
100                 'attrs' : flatatt(final_attrs),
101                 'js' : self.render_js(final_attrs['id']),
102             }
103         
104         return mark_safe(html)
105
106
107 class JQueryAutoCompleteField(forms.CharField):
108     def __init__(self, source, options=None, *args, **kwargs):
109         if 'widget' not in kwargs:
110             kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
111         
112         super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
113