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 _
17 from south.modelsinspector import add_introspection_rules
20 class JSONEncoder(json.JSONEncoder):
21 def default(self, obj):
22 if isinstance(obj, datetime.datetime):
23 return obj.strftime('%Y-%m-%d %H:%M:%S')
24 elif isinstance(obj, datetime.date):
25 return obj.strftime('%Y-%m-%d')
26 elif isinstance(obj, datetime.time):
27 return obj.strftime('%H:%M:%S')
28 return json.JSONEncoder.default(self, obj)
32 return JSONEncoder().encode(data)
36 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
39 class JSONFormField(forms.CharField):
40 widget = forms.Textarea
42 def clean(self, value):
47 raise forms.ValidationError(_('Enter a valid JSON value. Error: %s') % e)
50 class JSONField(models.TextField):
51 def formfield(self, **kwargs):
52 defaults = {'form_class': JSONFormField}
53 defaults.update(kwargs)
54 return super(JSONField, self).formfield(**defaults)
59 def get_internal_type(self):
62 def contribute_to_class(self, cls, name):
63 super(JSONField, self).contribute_to_class(cls, name)
65 def get_value(model_instance):
66 return loads(getattr(model_instance, self.attname, None))
67 setattr(cls, 'get_%s_value' % self.name, get_value)
69 def set_value(model_instance, json):
70 return setattr(model_instance, self.attname, dumps(json))
71 setattr(cls, 'set_%s_value' % self.name, set_value)
73 add_introspection_rules([], ["^catalogue\.fields\.JSONField"])
76 class JQueryAutoCompleteWidget(forms.TextInput):
77 def __init__(self, source, options=None, *args, **kwargs):
81 self.options = dumps(options)
82 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
84 def render_js(self, field_id):
85 source = "'%s'" % escape(self.source)
88 options += ', %s' % self.options
90 return u'$(\'#%s\').autocomplete(%s%s).result(autocomplete_result_handler);' % (field_id, source, options)
92 def render(self, name, value=None, attrs=None):
93 final_attrs = self.build_attrs(attrs, name=name)
95 final_attrs['value'] = smart_unicode(value)
97 if not self.attrs.has_key('id'):
98 final_attrs['id'] = 'id_%s' % name
100 html = u'''<input type="text" %(attrs)s/>
101 <script type="text/javascript">//<!--
104 'attrs' : flatatt(final_attrs),
105 'js' : self.render_js(final_attrs['id']),
108 return mark_safe(html)
111 class JQueryAutoCompleteField(forms.CharField):
112 def __init__(self, source, options=None, *args, **kwargs):
113 if 'widget' not in kwargs:
114 kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
116 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)
120 from south.modelsinspector import add_introspection_rules
122 add_introspection_rules([
124 [JSONField], # Class(es) these apply to
125 [], # Positional arguments (not used)
126 {}, # Keyword argument
127 ), ], ["^catalogue\.fields\.JSONField"])