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.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
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)
30 return JSONEncoder().encode(data)
34 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
37 class JSONFormField(forms.CharField):
38 widget = forms.Textarea
40 def clean(self, value):
45 raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
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)
57 def get_internal_type(self):
60 def contribute_to_class(self, cls, name):
61 super(JSONField, self).contribute_to_class(cls, name)
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)
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)
72 class JQueryAutoCompleteWidget(forms.TextInput):
73 def __init__(self, source, options=None, *args, **kwargs):
77 self.options = dumps(options)
78 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
80 def render_js(self, field_id):
81 source = "'%s'" % escape(self.source)
84 options += ', %s' % self.options
86 return u'$(\'#%s\').autocomplete(%s%s).result(autocomplete_result_handler);' % (field_id, source, options)
88 def render(self, name, value=None, attrs=None):
89 final_attrs = self.build_attrs(attrs, name=name)
91 final_attrs['value'] = smart_unicode(value)
93 if not self.attrs.has_key('id'):
94 final_attrs['id'] = 'id_%s' % name
96 html = u'''<input type="text" %(attrs)s/>
97 <script type="text/javascript">//<!--
100 'attrs' : flatatt(final_attrs),
101 'js' : self.render_js(final_attrs['id']),
104 return mark_safe(html)
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)
112 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)