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 import forms
10 from django.utils import simplejson as json
13 class JSONEncoder(json.JSONEncoder):
14 def default(self, obj):
15 if isinstance(obj, datetime.datetime):
16 return obj.strftime('%Y-%m-%d %H:%M:%S')
17 elif isinstance(obj, datetime.date):
18 return obj.strftime('%Y-%m-%d')
19 elif isinstance(obj, datetime.time):
20 return obj.strftime('%H:%M:%S')
21 return json.JSONEncoder.default(self, obj)
25 return JSONEncoder().encode(data)
29 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
32 class JSONFormField(forms.CharField):
33 widget = forms.Textarea
35 def clean(self, value):
40 raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
43 class JSONField(models.TextField):
44 def formfield(self, **kwargs):
45 defaults = {'form_class': JSONFormField}
46 defaults.update(kwargs)
47 return super(JSONField, self).formfield(**defaults)
52 def get_internal_type(self):
55 def contribute_to_class(self, cls, name):
56 super(JSONField, self).contribute_to_class(cls, name)
58 def get_value(model_instance):
59 return loads(getattr(model_instance, self.attname, None))
60 setattr(cls, 'get_%s_value' % self.name, get_value)
62 def set_value(model_instance, json):
63 return setattr(model_instance, self.attname, dumps(json))
64 setattr(cls, 'set_%s_value' % self.name, set_value)