ajaxable dialogs fixes,
[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 from functools import wraps
7
8 from django.conf import settings
9 from django.db import models
10 from django.db.models.fields.files import FieldFile
11 from django.db.models import signals
12 from django import forms
13 from django.forms.widgets import flatatt
14 from django.utils.encoding import smart_unicode
15 from django.utils import simplejson as json
16 from django.utils.html import escape
17 from django.utils.safestring import mark_safe
18 from django.utils.translation import ugettext_lazy as _
19
20
21 class JSONEncoder(json.JSONEncoder):
22     def default(self, obj):
23         if isinstance(obj, datetime.datetime):
24             return obj.strftime('%Y-%m-%d %H:%M:%S')
25         elif isinstance(obj, datetime.date):
26             return obj.strftime('%Y-%m-%d')
27         elif isinstance(obj, datetime.time):
28             return obj.strftime('%H:%M:%S')
29         return json.JSONEncoder.default(self, obj)
30
31
32 def dumps(data):
33     return JSONEncoder().encode(data)
34
35
36 def loads(str):
37     return json.loads(str, encoding=settings.DEFAULT_CHARSET)
38
39
40 class JSONFormField(forms.CharField):
41     widget = forms.Textarea
42
43     def clean(self, value):
44         try:
45             loads(value)
46             return value
47         except ValueError, e:
48             raise forms.ValidationError(_('Enter a valid JSON value. Error: %s') % e)
49
50
51 class JSONField(models.TextField):
52     def formfield(self, **kwargs):
53         defaults = {'form_class': JSONFormField}
54         defaults.update(kwargs)
55         return super(JSONField, self).formfield(**defaults)
56
57     def db_type(self, connection):
58         return 'text'
59
60     def get_internal_type(self):
61         return 'TextField'
62
63     def contribute_to_class(self, cls, name):
64         super(JSONField, self).contribute_to_class(cls, name)
65
66         def get_value(model_instance):
67             return loads(getattr(model_instance, self.attname, None))
68         setattr(cls, 'get_%s_value' % self.name, get_value)
69
70         def set_value(model_instance, json):
71             return setattr(model_instance, self.attname, dumps(json))
72         setattr(cls, 'set_%s_value' % self.name, set_value)
73
74
75 class JQueryAutoCompleteWidget(forms.TextInput):
76     def __init__(self, options, *args, **kwargs):
77         self.options = dumps(options)
78         super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
79
80     def render_js(self, field_id, options):
81         return u'$(\'#%s\').autocomplete(%s).result(autocomplete_result_handler);' % (field_id, 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'], self.options),
97             }
98
99         return mark_safe(html)
100
101
102 class JQueryAutoCompleteSearchWidget(JQueryAutoCompleteWidget):
103     def __init__(self, *args, **kwargs):
104         super(JQueryAutoCompleteSearchWidget, self).__init__(*args, **kwargs)
105
106     def render_js(self, field_id, options):
107         return u"""
108         $('#%s')
109         .autocomplete($.extend({
110           minLength: 0,
111           select: autocomplete_result_handler,
112           focus: function (ui, item) { return false; }
113         }, %s))
114         .data("autocomplete")._renderItem = autocomplete_format_item;
115         """ % (field_id, options)
116
117
118 class JQueryAutoCompleteField(forms.CharField):
119     def __init__(self, source, options={}, *args, **kwargs):
120         if 'widget' not in kwargs:
121             options['source'] = source
122             kwargs['widget'] = JQueryAutoCompleteWidget(options)
123
124         super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
125
126
127 class JQueryAutoCompleteSearchField(forms.CharField):
128     def __init__(self, source, options={}, *args, **kwargs):
129         if 'widget' not in kwargs:
130             options['source'] = source
131             kwargs['widget'] = JQueryAutoCompleteSearchWidget(options)
132
133         super(JQueryAutoCompleteSearchField, self).__init__(*args, **kwargs)
134
135
136 class OverwritingFieldFile(FieldFile):
137     """
138         Deletes the old file before saving the new one.
139     """
140
141     def save(self, name, content, *args, **kwargs):
142         leave = kwargs.pop('leave', None)
143         # delete if there's a file already and there's a new one coming
144         if not leave and self and (not hasattr(content, 'path') or
145                                    content.path != self.path):
146             self.delete(save=False)
147         return super(OverwritingFieldFile, self).save(
148                 name, content, *args, **kwargs)
149
150
151 class OverwritingFileField(models.FileField):
152     attr_class = OverwritingFieldFile
153
154
155 try:
156     # check for south
157     from south.modelsinspector import add_introspection_rules
158
159     add_introspection_rules([], ["^catalogue\.fields\.JSONField"])
160     add_introspection_rules([], ["^catalogue\.fields\.OverwritingFileField"])
161 except ImportError:
162     pass