"""Simple JSON field that stores python structures as JSON strings
on database.
"""
-
__metaclass__ = models.SubfieldBase
def to_python(self, value):
try:
return simplejson.loads(value)
except Exception, e:
- raise ValidationError(str(e))
+ raise ValidationError(e.message)
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
- super(JSONField, self).validate(value, model_instance)
- try:
- return simplejson.loads(value)
- except Exception, e:
- raise ValidationError(str(e))
+ if isinstance(value, basestring):
+ super(JSONField, self).validate(value, model_instance)
+ try:
+ simplejson.loads(value)
+ except Exception, e:
+ raise ValidationError(e.message)
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
- raise ValidationError(str(e))
+ raise ValidationError(e.message)
def value_to_string(self, obj):
"""Return value from object converted to string properly"""
return smart_unicode(self.get_prep_value(self._get_val_from_obj(obj)))
+ def value_from_object(self, obj):
+ """Return value dumped to string."""
+ return self.get_prep_value(self._get_val_from_obj(obj))
+
try:
from south.modelsinspector import add_introspection_rules