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
11 from south.modelsinspector import add_introspection_rules
14 class JSONEncoder(json.JSONEncoder):
15 def default(self, obj):
16 if isinstance(obj, datetime.datetime):
17 return obj.strftime('%Y-%m-%d %H:%M:%S')
18 elif isinstance(obj, datetime.date):
19 return obj.strftime('%Y-%m-%d')
20 elif isinstance(obj, datetime.time):
21 return obj.strftime('%H:%M:%S')
22 return json.JSONEncoder.default(self, obj)
26 return JSONEncoder().encode(data)
30 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
33 class JSONFormField(forms.CharField):
34 widget = forms.Textarea
36 def clean(self, value):
41 raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
44 class JSONField(models.TextField):
45 def formfield(self, **kwargs):
46 defaults = {'form_class': JSONFormField}
47 defaults.update(kwargs)
48 return super(JSONField, self).formfield(**defaults)
50 def db_type(self, connection):
53 def get_internal_type(self):
56 def contribute_to_class(self, cls, name):
57 super(JSONField, self).contribute_to_class(cls, name)
59 def get_value(model_instance):
60 return loads(getattr(model_instance, self.attname, None))
61 setattr(cls, 'get_%s_value' % self.name, get_value)
63 def set_value(model_instance, json):
64 return setattr(model_instance, self.attname, dumps(json))
65 setattr(cls, 'set_%s_value' % self.name, set_value)
67 add_introspection_rules([], [r"^sponsors\.fields\.JSONField"])