]> git.parisson.com Git - django-social-auth.git/commitdiff
Store extra data in JSON format, also add method to extend extra values to store...
authorMatías Aguirre <matiasaguirre@gmail.com>
Wed, 23 Feb 2011 19:44:24 +0000 (17:44 -0200)
committerMatías Aguirre <matiasaguirre@gmail.com>
Wed, 23 Feb 2011 20:24:00 +0000 (18:24 -0200)
social_auth/fields.py [new file with mode: 0644]

diff --git a/social_auth/fields.py b/social_auth/fields.py
new file mode 100644 (file)
index 0000000..ec52d9a
--- /dev/null
@@ -0,0 +1,43 @@
+from django.core.exceptions import ValidationError
+from django.db import models
+from django.utils import simplejson
+
+
+class JSONField(models.TextField):
+    """Simple JSON field that stores python structures as JSON strings
+    on database.
+    """
+
+    __metaclass__ = models.SubfieldBase
+
+    def to_python(self, value):
+        """
+        Convert the input JSON value into python structures, raises
+        django.core.exceptions.ValidationError if the data can't be converted.
+        """
+        if self.blank and not value:
+            return None
+        if isinstance(value, basestring):
+            try:
+                return simplejson.loads(value)
+            except Exception, e:
+                raise ValidationError(str(e))
+        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))
+
+    def get_db_prep_save(self, value):
+        """Convert value to JSON string before save"""
+        try:
+            value = simplejson.dumps(value)
+        except Exception, e:
+            raise ValidationError(str(e))
+        return super(JSONField, self).get_db_prep_save(value)