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.
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.utils.encoding 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 from django.utils.translation import ugettext_lazy as _
19 class JSONEncoder(json.JSONEncoder):
20 def default(self, obj):
21 if isinstance(obj, datetime.datetime):
22 return obj.strftime('%Y-%m-%d %H:%M:%S')
23 elif isinstance(obj, datetime.date):
24 return obj.strftime('%Y-%m-%d')
25 elif isinstance(obj, datetime.time):
26 return obj.strftime('%H:%M:%S')
27 return json.JSONEncoder.default(self, obj)
31 return JSONEncoder().encode(data)
35 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
38 class JSONFormField(forms.CharField):
39 widget = forms.Textarea
41 def clean(self, value):
46 raise forms.ValidationError(_('Enter a valid JSON value. Error: %s') % e)
49 class JSONField(models.TextField):
50 def formfield(self, **kwargs):
51 defaults = {'form_class': JSONFormField}
52 defaults.update(kwargs)
53 return super(JSONField, self).formfield(**defaults)
55 def db_type(self, connection):
58 def get_internal_type(self):
61 def contribute_to_class(self, cls, name):
62 super(JSONField, self).contribute_to_class(cls, name)
64 def get_value(model_instance):
65 return loads(getattr(model_instance, self.attname, None))
66 setattr(cls, 'get_%s_value' % self.name, get_value)
68 def set_value(model_instance, json):
69 return setattr(model_instance, self.attname, dumps(json))
70 setattr(cls, 'set_%s_value' % self.name, set_value)
73 class JQueryAutoCompleteWidget(forms.TextInput):
74 def __init__(self, source, options=None, *args, **kwargs):
78 self.options = dumps(options)
79 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
81 def render_js(self, field_id):
82 source = "'%s'" % escape(self.source)
85 options += ', %s' % self.options
87 return u'$(\'#%s\').autocomplete(%s%s).result(autocomplete_result_handler);' % (field_id, source, options)
89 def render(self, name, value=None, attrs=None):
90 final_attrs = self.build_attrs(attrs, name=name)
92 final_attrs['value'] = smart_unicode(value)
94 if not self.attrs.has_key('id'):
95 final_attrs['id'] = 'id_%s' % name
97 html = u'''<input type="text" %(attrs)s/>
98 <script type="text/javascript">//<!--
101 'attrs' : flatatt(final_attrs),
102 'js' : self.render_js(final_attrs['id']),
105 return mark_safe(html)
108 class JQueryAutoCompleteField(forms.CharField):
109 def __init__(self, source, options=None, *args, **kwargs):
110 if 'widget' not in kwargs:
111 kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
113 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
117 from south.modelsinspector import add_introspection_rules
119 add_introspection_rules([
121 [JSONField], # Class(es) these apply to
122 [], # Positional arguments (not used)
123 {}, # Keyword argument
124 ), ], ["^catalogue\.fields\.JSONField"])