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.
6 from functools import wraps
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 _
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)
33 return JSONEncoder().encode(data)
37 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
40 class JSONFormField(forms.CharField):
41 widget = forms.Textarea
43 def clean(self, value):
48 raise forms.ValidationError(_('Enter a valid JSON value. Error: %s') % e)
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)
57 def db_type(self, connection):
60 def get_internal_type(self):
63 def contribute_to_class(self, cls, name):
64 super(JSONField, self).contribute_to_class(cls, name)
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)
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)
75 class JQueryAutoCompleteWidget(forms.TextInput):
76 def __init__(self, source, options=None, *args, **kwargs):
80 self.options = dumps(options)
81 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
83 def render_js(self, field_id):
84 source = "'%s'" % escape(self.source)
87 options += ', %s' % self.options
89 return u'$(\'#%s\').autocomplete(%s%s).result(autocomplete_result_handler);' % (field_id, source, options)
91 def render(self, name, value=None, attrs=None):
92 final_attrs = self.build_attrs(attrs, name=name)
94 final_attrs['value'] = smart_unicode(value)
96 if not self.attrs.has_key('id'):
97 final_attrs['id'] = 'id_%s' % name
99 html = u'''<input type="text" %(attrs)s/>
100 <script type="text/javascript">//<!--
103 'attrs' : flatatt(final_attrs),
104 'js' : self.render_js(final_attrs['id']),
107 return mark_safe(html)
110 class JQueryAutoCompleteField(forms.CharField):
111 def __init__(self, source, options=None, *args, **kwargs):
112 if 'widget' not in kwargs:
113 kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
115 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
119 from south.modelsinspector import add_introspection_rules
121 add_introspection_rules([
123 [JSONField], # Class(es) these apply to
124 [], # Positional arguments (not used)
125 {}, # Keyword argument
126 ), ], ["^catalogue\.fields\.JSONField"])
131 class OverwritingFieldFile(FieldFile):
133 Deletes the old file before saving the new one.
136 def save(self, name, content, *args, **kwargs):
137 leave = kwargs.pop('leave', None)
138 if not leave and self and content is not self:
139 self.delete(save=False)
140 return super(OverwritingFieldFile, self).save(name, content, *args, **kwargs)
143 class OverwritingFileField(models.FileField):
144 attr_class = OverwritingFieldFile