Commits

Zakhar Zibarov committed eebb22e

Added get_default() to work with fields with default values

Comments (0)

Files changed (3)

jsonfield/fields.py

         return o.strftime("%Y-%m-%d")
     if isinstance(o, datetime.time):
         return o.strftime("%H:%M:%S")
-        
+
     raise TypeError(repr(o) + " is not JSON serializable")
 
 
     A field that will ensure the data entered into it is valid JSON.
     """
     __metaclass__ = models.SubfieldBase
-    
+
     description = "JSON object"
-    
+
     def formfield(self, **kwargs):
         return super(JSONField, self).formfield(form_class=JSONFormField, **kwargs)
 
+    def get_default(self):
+        if self.has_default():
+            if callable(self.default):
+                return self.default()
+            return self.default
+        return super(JSONField, self).get_default()
+
     def to_python(self, value):
         if isinstance(value, basestring):
             if value == '':
         return value
 
     def get_db_prep_value(self, value, connection=None, prepared=None):
-        if value is None: 
+        if value is None:
             return None
         return json.dumps(value, default=default)
 

jsonfield/tests/base.py

 from django.db import connection
 from django.db import models
 
-from jsonfield.tests.jsonfield_test_app.models import JSONFieldTestModel
+from jsonfield.tests.jsonfield_test_app.models import JSONFieldTestModel, \
+                                                      JSONFieldWithDefaultTestModel
 from jsonfield import JSONField
 
 class JSONFieldTest(DjangoTestCase):
 
     def test_json_field_save(self):
         obj = JSONFieldTestModel.objects.create(
-            id=10, 
+            id=10,
             json='''{
                 "spam": "eggs"
             }''',
         formfield = field.formfield()
         self.assertEquals(type(formfield), JSONFormField)
         self.assertEquals(type(formfield.widget), JSONWidget)
+
+    def test_default_value(self):
+        obj = JSONFieldWithDefaultTestModel.objects.create()
+        obj = JSONFieldWithDefaultTestModel.objects.get(id=obj.id)
+        self.assertEquals(obj.json, {'sukasuka': 'YAAAAAZ'})

jsonfield/tests/jsonfield_test_app/models.py

 
 class JSONFieldTestModel(models.Model):
     json = JSONField(u"test", null=True, blank=True)
+
+class JSONFieldWithDefaultTestModel(models.Model):
+    json = JSONField(default={"sukasuka": "YAAAAAZ"})