1 # -*- coding: utf-8 -*-
4 from django.conf import settings
5 from django.db import models
6 from django import forms
7 from django.utils import simplejson as json
10 class JSONEncoder(json.JSONEncoder):
11 def default(self, obj):
12 if isinstance(obj, datetime.datetime):
13 return obj.strftime('%Y-%m-%dT%H:%M:%S')
14 elif isinstance(obj, datetime.date):
15 return obj.strftime('%Y-%m-%d')
16 elif isinstance(obj, datetime.time):
17 return obj.strftime('%H:%M:%S')
18 return json.JSONEncoder.default(self, obj)
22 return JSONEncoder().encode(data)
26 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
29 class JSONFormField(forms.CharField):
30 widget = forms.Textarea
32 def clean(self, value):
37 raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
40 class JSONField(models.TextField):
41 def formfield(self, **kwargs):
42 defaults = {'form_class': JSONFormField}
43 defaults.update(kwargs)
44 return super(JSONField, self).formfield(**defaults)
49 def get_internal_type(self):
52 def contribute_to_class(self, cls, name):
53 super(JSONField, self).contribute_to_class(cls, name)
55 def get_value(model_instance):
56 return loads(getattr(model_instance, self.attname, None))
57 setattr(cls, 'get_%s_value' % self.name, get_value)
59 def set_value(model_instance, json):
60 return setattr(model_instance, self.attname, dumps(json))
61 setattr(cls, 'set_%s_value' % self.name, set_value)