[Python-modules-commits] [python-django-jsonfield] 01/03: Import python-django-jsonfield_0.9.15.orig.tar.gz

Raphaël Hertzog hertzog at moszumanska.debian.org
Mon Oct 19 18:51:16 UTC 2015


This is an automated email from the git hooks/post-receive script.

hertzog pushed a commit to branch master
in repository python-django-jsonfield.

commit ab69f7be886567deb0eb386ce3e7f93ca0294f8a
Author: Raphaël Hertzog <hertzog at debian.org>
Date:   Mon Oct 19 20:41:38 2015 +0200

    Import python-django-jsonfield_0.9.15.orig.tar.gz
---
 LICENSE                                      |  2 +-
 PKG-INFO                                     | 23 ++++++----
 README.rst                                   | 20 ++++++---
 django_jsonfield.egg-info/PKG-INFO           | 23 ++++++----
 jsonfield/VERSION                            |  2 +-
 jsonfield/__init__.py                        |  6 +--
 jsonfield/fields.py                          | 63 +++++++++++++---------------
 jsonfield/forms.py                           |  6 +--
 jsonfield/templatetags/jsonify.py            |  1 +
 jsonfield/tests/__init__.py                  |  4 +-
 jsonfield/tests/jsonfield_test_app/forms.py  |  4 ++
 jsonfield/tests/jsonfield_test_app/models.py | 12 ++++--
 jsonfield/tests/test_fields.py               | 44 +++++++++++--------
 jsonfield/tests/test_forms.py                | 36 +++++++++-------
 jsonfield/utils.py                           |  6 ++-
 jsonfield/widgets.py                         |  7 ++--
 setup.py                                     |  1 +
 tests.py                                     | 24 +++++------
 18 files changed, 166 insertions(+), 118 deletions(-)

diff --git a/LICENSE b/LICENSE
index 69b109b..d869f75 100644
--- a/LICENSE
+++ b/LICENSE
@@ -8,7 +8,7 @@ modification, are permitted provided that the following conditions are met:
     * Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
-    * The names of its contributors may be used to endorse or promote products
+    * The names of its contributors may not be used to endorse or promote products
       derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
diff --git a/PKG-INFO b/PKG-INFO
index a72c499..4c30111 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: django-jsonfield
-Version: 0.9.13
+Version: 0.9.15
 Summary: JSONField for django models
 Home-page: http://bitbucket.org/schinckel/django-jsonfield/
 Author: Matthew Schinckel
@@ -25,10 +25,10 @@ Description: django-jsonfield
         
             from django.db import models
             import jsonfield
-            
+        
             class MyModel(models.Model):
                 the_json = jsonfield.JSONField()
-            
+        
         Now, it will validate the JSON on entry, and store it as a string in the
         database.  When you instantiate/fetch the object, it will be turned back
         into a python list/dict/string.
@@ -52,14 +52,22 @@ Description: django-jsonfield
         This allows you to convert a python data structure into JSON within a template::
         
             {% load jsonify %}
-            
+        
             <script>
             var foo = {{ bar|jsonify }};
             </script>
-          
+        
         History
         ----------
         
+        0.9.15
+        ~~~~~~
+        Bump version number to get around uploading issues.
+        
+        0.9.14
+        ~~~~~~
+        No longer hit the db to work out db_type.
+        
         0.9.12
         ~~~~~~
         Cache the result of db_type.
@@ -92,7 +100,7 @@ Description: django-jsonfield
         Add LICENSE file.
         Added TypedJSONField.
         
-         
+        
         0.8.10
         ~~~~~~
         Allow ``{{ variable|jsonify }}`` to work with querysets.
@@ -156,7 +164,7 @@ Description: django-jsonfield
         ----------
         Allow for passing in a function to use for processing unknown data types.
         
-        Convert date/time objects nicely to/from ISO strings (YYYY-mm-dd HH:MM:SS 
+        Convert date/time objects nicely to/from ISO strings (YYYY-mm-dd HH:MM:SS
         TZNAME). This is actually a bit tricky, as we don't know if we are expecting
         a date/time object. We may parse objects as we go, but there could be
         some performance issues with this. I'm tempted to say "only do this on TypedJSONField()"
@@ -166,6 +174,7 @@ Description: django-jsonfield
         
 Platform: UNKNOWN
 Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
 Classifier: License :: OSI Approved :: BSD License
 Classifier: Operating System :: OS Independent
 Classifier: Framework :: Django
diff --git a/README.rst b/README.rst
index c258523..97b4c60 100644
--- a/README.rst
+++ b/README.rst
@@ -17,10 +17,10 @@ To use, just install the package, and then use the field::
 
     from django.db import models
     import jsonfield
-    
+
     class MyModel(models.Model):
         the_json = jsonfield.JSONField()
-    
+
 Now, it will validate the JSON on entry, and store it as a string in the
 database.  When you instantiate/fetch the object, it will be turned back
 into a python list/dict/string.
@@ -44,14 +44,22 @@ jsonify templatetag
 This allows you to convert a python data structure into JSON within a template::
 
     {% load jsonify %}
-    
+
     <script>
     var foo = {{ bar|jsonify }};
     </script>
-  
+
 History
 ----------
 
+0.9.15
+~~~~~~
+Bump version number to get around uploading issues.
+
+0.9.14
+~~~~~~
+No longer hit the db to work out db_type.
+
 0.9.12
 ~~~~~~
 Cache the result of db_type.
@@ -84,7 +92,7 @@ Remove support for django < 1.3.
 Add LICENSE file.
 Added TypedJSONField.
 
- 
+
 0.8.10
 ~~~~~~
 Allow ``{{ variable|jsonify }}`` to work with querysets.
@@ -148,7 +156,7 @@ Todo
 ----------
 Allow for passing in a function to use for processing unknown data types.
 
-Convert date/time objects nicely to/from ISO strings (YYYY-mm-dd HH:MM:SS 
+Convert date/time objects nicely to/from ISO strings (YYYY-mm-dd HH:MM:SS
 TZNAME). This is actually a bit tricky, as we don't know if we are expecting
 a date/time object. We may parse objects as we go, but there could be
 some performance issues with this. I'm tempted to say "only do this on TypedJSONField()"
diff --git a/django_jsonfield.egg-info/PKG-INFO b/django_jsonfield.egg-info/PKG-INFO
index a72c499..4c30111 100644
--- a/django_jsonfield.egg-info/PKG-INFO
+++ b/django_jsonfield.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: django-jsonfield
-Version: 0.9.13
+Version: 0.9.15
 Summary: JSONField for django models
 Home-page: http://bitbucket.org/schinckel/django-jsonfield/
 Author: Matthew Schinckel
@@ -25,10 +25,10 @@ Description: django-jsonfield
         
             from django.db import models
             import jsonfield
-            
+        
             class MyModel(models.Model):
                 the_json = jsonfield.JSONField()
-            
+        
         Now, it will validate the JSON on entry, and store it as a string in the
         database.  When you instantiate/fetch the object, it will be turned back
         into a python list/dict/string.
@@ -52,14 +52,22 @@ Description: django-jsonfield
         This allows you to convert a python data structure into JSON within a template::
         
             {% load jsonify %}
-            
+        
             <script>
             var foo = {{ bar|jsonify }};
             </script>
-          
+        
         History
         ----------
         
+        0.9.15
+        ~~~~~~
+        Bump version number to get around uploading issues.
+        
+        0.9.14
+        ~~~~~~
+        No longer hit the db to work out db_type.
+        
         0.9.12
         ~~~~~~
         Cache the result of db_type.
@@ -92,7 +100,7 @@ Description: django-jsonfield
         Add LICENSE file.
         Added TypedJSONField.
         
-         
+        
         0.8.10
         ~~~~~~
         Allow ``{{ variable|jsonify }}`` to work with querysets.
@@ -156,7 +164,7 @@ Description: django-jsonfield
         ----------
         Allow for passing in a function to use for processing unknown data types.
         
-        Convert date/time objects nicely to/from ISO strings (YYYY-mm-dd HH:MM:SS 
+        Convert date/time objects nicely to/from ISO strings (YYYY-mm-dd HH:MM:SS
         TZNAME). This is actually a bit tricky, as we don't know if we are expecting
         a date/time object. We may parse objects as we go, but there could be
         some performance issues with this. I'm tempted to say "only do this on TypedJSONField()"
@@ -166,6 +174,7 @@ Description: django-jsonfield
         
 Platform: UNKNOWN
 Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
 Classifier: License :: OSI Approved :: BSD License
 Classifier: Operating System :: OS Independent
 Classifier: Framework :: Django
diff --git a/jsonfield/VERSION b/jsonfield/VERSION
index 62ea259..5d11b14 100644
--- a/jsonfield/VERSION
+++ b/jsonfield/VERSION
@@ -1 +1 @@
-0.9.13
+0.9.15
diff --git a/jsonfield/__init__.py b/jsonfield/__init__.py
index 0bf34dc..10b91dc 100644
--- a/jsonfield/__init__.py
+++ b/jsonfield/__init__.py
@@ -1,7 +1,7 @@
 import os
-__version__ = open(os.path.join(os.path.dirname(__file__),'VERSION')).read().strip()
+__version__ = open(os.path.join(os.path.dirname(__file__), 'VERSION')).read().strip()
 
 try:
-    from .fields import JSONField
+    from .fields import JSONField  # NOQA
 except ImportError:
-    pass
\ No newline at end of file
+    pass
diff --git a/jsonfield/fields.py b/jsonfield/fields.py
index 433ac0c..a4487c7 100644
--- a/jsonfield/fields.py
+++ b/jsonfield/fields.py
@@ -21,6 +21,7 @@ DB_TYPE_CACHE_KEY = (
     '%(ENGINE)s:%(HOST)s:%(PORT)s:%(NAME)s'
 )
 
+
 class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
     """
     A field that will ensure the data entered into it is valid JSON.
@@ -29,7 +30,7 @@ class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
         'invalid': _("'%s' is not a valid JSON string.")
     }
     description = "JSON object"
-    
+
     def __init__(self, *args, **kwargs):
         if not kwargs.get('null', False):
             kwargs['default'] = kwargs.get('default', dict)
@@ -38,7 +39,7 @@ class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
         }
         super(JSONField, self).__init__(*args, **kwargs)
         self.validate(self.get_default(), None)
-        
+
     def formfield(self, **kwargs):
         defaults = {
             'form_class': JSONFormField,
@@ -46,13 +47,13 @@ class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
         }
         defaults.update(**kwargs)
         return super(JSONField, self).formfield(**defaults)
-    
+
     def validate(self, value, model_instance):
         if not self.null and value is None:
             raise ValidationError(self.error_messages['null'])
         try:
             self.get_prep_value(value)
-        except:
+        except ValueError:
             raise ValidationError(self.error_messages['invalid'] % value)
 
     def get_default(self):
@@ -67,26 +68,17 @@ class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
 
     def get_internal_type(self):
         return 'TextField'
-    
+
     def db_type(self, connection):
-        cache_key = DB_TYPE_CACHE_KEY % connection.settings_dict
-        db_type = cache.get(cache_key)
-        
-        if not db_type:
-            # Test to see if we support JSON querying.
-            cursor = connection.cursor()
-            try:
-                sid = transaction.savepoint(using=connection.alias)
-                cursor.execute('SELECT \'{}\'::json = \'{}\'::json;')
-            except DatabaseError:
-                transaction.savepoint_rollback(sid, using=connection.alias)
-                db_type = 'text'
-            else:
-                db_type = 'json'
-            cache.set(cache_key, db_type)
-        
-        return db_type
-    
+        if connection.vendor == 'postgresql':
+            # Only do jsonb if in pg 9.4+
+            if connection.pg_version >= 90400:
+                return 'jsonb'
+            return 'text'
+        if connection.vendor == 'mysql':
+            return 'longtext'
+        return 'text'
+
     def to_python(self, value):
         if isinstance(value, six.string_types):
             if value == "":
@@ -104,14 +96,14 @@ class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
 
     def get_db_prep_value(self, value, connection=None, prepared=None):
         return self.get_prep_value(value)
-    
+
     def get_prep_value(self, value):
         if value is None:
             if not self.null and self.blank:
                 return ""
             return None
         return json.dumps(value, default=default, **self.encoder_kwargs)
-    
+
     def get_prep_lookup(self, lookup_type, value):
         if lookup_type in ["exact", "iexact"]:
             return self.to_python(self.get_prep_value(value))
@@ -134,46 +126,47 @@ class JSONField(six.with_metaclass(models.SubfieldBase, models.Field)):
     def value_to_string(self, obj):
         return self._get_val_from_obj(obj)
 
+
 class TypedJSONField(JSONField):
     """
-    
+
     """
     def __init__(self, *args, **kwargs):
         self.json_required_fields = kwargs.pop('required_fields', {})
         self.json_validators = kwargs.pop('validators', [])
-        
+
         super(TypedJSONField, self).__init__(*args, **kwargs)
-    
+
     def cast_required_fields(self, obj):
         if not obj:
             return
         for field_name, field_type in self.json_required_fields.items():
             obj[field_name] = field_type.to_python(obj[field_name])
-        
+
     def to_python(self, value):
         value = super(TypedJSONField, self).to_python(value)
-        
+
         if isinstance(value, list):
             for item in value:
                 self.cast_required_fields(item)
         else:
             self.cast_required_fields(value)
-        
+
         return value
-    
+
     def validate(self, value, model_instance):
         super(TypedJSONField, self).validate(value, model_instance)
-        
+
         for v in self.json_validators:
             if isinstance(value, list):
                 for item in value:
                     v(item)
             else:
                 v(value)
-    
+
 try:
     from south.modelsinspector import add_introspection_rules
     add_introspection_rules([], ['^jsonfield\.fields\.JSONField'])
     add_introspection_rules([], ['^jsonfield\.fields\.TypedJSONField'])
 except ImportError:
-    pass
\ No newline at end of file
+    pass
diff --git a/jsonfield/forms.py b/jsonfield/forms.py
index 7d26c6e..68ebcea 100644
--- a/jsonfield/forms.py
+++ b/jsonfield/forms.py
@@ -8,7 +8,7 @@ from .widgets import JSONWidget
 
 class JSONFormField(forms.CharField):
     empty_values = [None, '']
-    
+
     def __init__(self, *args, **kwargs):
         if 'widget' not in kwargs:
             kwargs['widget'] = JSONWidget
@@ -24,8 +24,8 @@ class JSONFormField(forms.CharField):
                 )
         else:
             return value
-    
+
     def validate(self, value):
         # This is required in older django versions.
         if value in self.empty_values and self.required:
-            raise forms.ValidationError(self.error_messages['required'], code='required')
\ No newline at end of file
+            raise forms.ValidationError(self.error_messages['required'], code='required')
diff --git a/jsonfield/templatetags/jsonify.py b/jsonfield/templatetags/jsonify.py
index da20e98..8d94a6d 100644
--- a/jsonfield/templatetags/jsonify.py
+++ b/jsonfield/templatetags/jsonify.py
@@ -6,6 +6,7 @@ from jsonfield.utils import TZAwareJSONEncoder
 
 register = template.Library()
 
+
 @register.filter
 def jsonify(value):
     # If we have a queryset, then convert it into a list.
diff --git a/jsonfield/tests/__init__.py b/jsonfield/tests/__init__.py
index d017229..c8f487c 100644
--- a/jsonfield/tests/__init__.py
+++ b/jsonfield/tests/__init__.py
@@ -1,2 +1,2 @@
-from .test_fields import *
-from .test_forms import *
\ No newline at end of file
+from .test_fields import *  # NOQA
+from .test_forms import *   # NOQA
diff --git a/jsonfield/tests/jsonfield_test_app/forms.py b/jsonfield/tests/jsonfield_test_app/forms.py
index ec546d6..bd8d5a0 100644
--- a/jsonfield/tests/jsonfield_test_app/forms.py
+++ b/jsonfield/tests/jsonfield_test_app/forms.py
@@ -3,10 +3,14 @@ from django import forms
 from jsonfield.forms import JSONFormField
 from .models import JSONFieldTestModel
 
+
 class JSONTestForm(forms.Form):
     json_data = JSONFormField()
     optional_json_data = JSONFormField(required=False)
 
+
 class JSONTestModelForm(forms.ModelForm):
+
     class Meta:
         model = JSONFieldTestModel
+        exclude = []
diff --git a/jsonfield/tests/jsonfield_test_app/models.py b/jsonfield/tests/jsonfield_test_app/models.py
index f4545e1..eb3781e 100644
--- a/jsonfield/tests/jsonfield_test_app/models.py
+++ b/jsonfield/tests/jsonfield_test_app/models.py
@@ -1,13 +1,17 @@
 from django.db import models
 from jsonfield.fields import JSONField
 
+
 class JSONFieldTestModel(models.Model):
     json = JSONField("test", null=True, blank=True)
+
     class Meta:
         app_label = 'jsonfield'
 
+
 class JSONFieldWithDefaultTestModel(models.Model):
     json = JSONField(default={"sukasuka": "YAAAAAZ"})
+
     class Meta:
         app_label = 'jsonfield'
 
@@ -15,11 +19,13 @@ class JSONFieldWithDefaultTestModel(models.Model):
 class BlankJSONFieldTestModel(models.Model):
     null_json = JSONField(null=True)
     blank_json = JSONField(blank=True)
+
     class Meta:
         app_label = 'jsonfield'
 
+
 class CallableDefaultModel(models.Model):
-    json = JSONField(default=lambda:{'x':2})
-    
+    json = JSONField(default=lambda: {'x': 2})
+
     class Meta:
-        app_label = 'jsonfield'
\ No newline at end of file
+        app_label = 'jsonfield'
diff --git a/jsonfield/tests/test_fields.py b/jsonfield/tests/test_fields.py
index 7b37320..ec779a7 100644
--- a/jsonfield/tests/test_fields.py
+++ b/jsonfield/tests/test_fields.py
@@ -1,18 +1,20 @@
 #:coding=utf-8:
+import unittest
+
 from django.test import TestCase as DjangoTestCase
-from django.utils import unittest
 from django.utils.encoding import force_text
 from django import forms
 
-from jsonfield.tests.jsonfield_test_app.models import *
+from jsonfield.tests.jsonfield_test_app.models import *  # NOQA
 from jsonfield.fields import JSONField
 
+
 class JSONFieldTest(DjangoTestCase):
     def test_json_field(self):
         obj = JSONFieldTestModel(json='''{
             "spam": "eggs"
         }''')
-        self.assertEqual(obj.json, {'spam':'eggs'})
+        self.assertEqual(obj.json, {'spam': 'eggs'})
 
     def test_json_field_empty(self):
         obj = JSONFieldTestModel(json='')
@@ -26,7 +28,7 @@ class JSONFieldTest(DjangoTestCase):
             }''',
         )
         obj2 = JSONFieldTestModel.objects.get(id=10)
-        self.assertEqual(obj2.json, {'spam':'eggs'})
+        self.assertEqual(obj2.json, {'spam': 'eggs'})
 
     def test_json_field_save_empty(self):
         JSONFieldTestModel.objects.create(id=10, json='')
@@ -87,24 +89,24 @@ class JSONFieldTest(DjangoTestCase):
 
     def test_query_object(self):
         JSONFieldTestModel.objects.create(json={})
-        JSONFieldTestModel.objects.create(json={'foo':'bar'})
+        JSONFieldTestModel.objects.create(json={'foo': 'bar'})
         self.assertEqual(2, JSONFieldTestModel.objects.all().count())
         self.assertEqual(1, JSONFieldTestModel.objects.exclude(json={}).count())
         self.assertEqual(1, JSONFieldTestModel.objects.filter(json={}).count())
-        self.assertEqual(1, JSONFieldTestModel.objects.filter(json={'foo':'bar'}).count())
-        self.assertEqual(1, JSONFieldTestModel.objects.filter(json__contains={'foo':'bar'}).count())
-        JSONFieldTestModel.objects.create(json={'foo':'bar', 'baz':'bing'})
-        self.assertEqual(2, JSONFieldTestModel.objects.filter(json__contains={'foo':'bar'}).count())
+        self.assertEqual(1, JSONFieldTestModel.objects.filter(json={'foo': 'bar'}).count())
+        self.assertEqual(1, JSONFieldTestModel.objects.filter(json__contains={'foo': 'bar'}).count())
+        JSONFieldTestModel.objects.create(json={'foo': 'bar', 'baz': 'bing'})
+        self.assertEqual(2, JSONFieldTestModel.objects.filter(json__contains={'foo': 'bar'}).count())
         # This next one is a bit hard to do without proper lookups, which I'm unlikely to implement.
-        #self.assertEqual(1, JSONFieldTestModel.objects.filter(json__contains={'baz':'bing', 'foo':'bar'}).count())
+        # self.assertEqual(1, JSONFieldTestModel.objects.filter(json__contains={'baz':'bing', 'foo':'bar'}).count())
         self.assertEqual(2, JSONFieldTestModel.objects.filter(json__contains='foo').count())
         # This code needs to be implemented!
-        self.assertRaises(TypeError, lambda:JSONFieldTestModel.objects.filter(json__contains=['baz', 'foo']))
+        self.assertRaises(TypeError, lambda: JSONFieldTestModel.objects.filter(json__contains=['baz', 'foo']))
 
     def test_query_isnull(self):
         JSONFieldTestModel.objects.create(json=None)
         JSONFieldTestModel.objects.create(json={})
-        JSONFieldTestModel.objects.create(json={'foo':'bar'})
+        JSONFieldTestModel.objects.create(json={'foo': 'bar'})
 
         self.assertEqual(1, JSONFieldTestModel.objects.filter(json=None).count())
         self.assertEqual(None, JSONFieldTestModel.objects.get(json=None).json)
@@ -122,12 +124,12 @@ class JSONFieldTest(DjangoTestCase):
     def test_callable_default(self):
         CallableDefaultModel.objects.create()
         obj = CallableDefaultModel.objects.get()
-        self.assertEqual({'x':2}, obj.json)
+        self.assertEqual({'x': 2}, obj.json)
 
     def test_callable_default_overridden(self):
-        CallableDefaultModel.objects.create(json={'x':3})
+        CallableDefaultModel.objects.create(json={'x': 3})
         obj = CallableDefaultModel.objects.get()
-        self.assertEqual({'x':3}, obj.json)
+        self.assertEqual({'x': 3}, obj.json)
 
     def test_mutable_default_checking(self):
         obj1 = JSONFieldWithDefaultTestModel()
@@ -145,13 +147,19 @@ class JSONFieldTest(DjangoTestCase):
 
     def test_invalid_json_default(self):
         with self.assertRaises(ValueError):
-            field = JSONField('test', default='{"foo"}')
+            JSONField('test', default='{"foo"}')
 
     def test_indent(self):
-        field = JSONField('test', indent=2)
+        JSONField('test', indent=2)
+
+    @unittest.expectedFailure
+    def test_string_is_valid_json(self):
+        JSONFieldTestModel.objects.create(json='"foo"')
+        self.assertEqual('foo', JSONFieldTestModel.objects.get().json)
+
 
 class SavingModelsTest(DjangoTestCase):
     def test_saving_null(self):
         obj = BlankJSONFieldTestModel.objects.create(blank_json='', null_json=None)
         self.assertEqual('', obj.blank_json)
-        self.assertEqual(None, obj.null_json)
\ No newline at end of file
+        self.assertEqual(None, obj.null_json)
diff --git a/jsonfield/tests/test_forms.py b/jsonfield/tests/test_forms.py
index aa81adc..6f51e74 100644
--- a/jsonfield/tests/test_forms.py
+++ b/jsonfield/tests/test_forms.py
@@ -1,56 +1,62 @@
 from django.test import TestCase as DjangoTestCase
-from django.utils import unittest
 from django.forms import ValidationError
 
 from jsonfield.forms import JSONFormField
-from jsonfield.tests.jsonfield_test_app.forms import JSONTestForm, JSONTestModelForm
+from jsonfield.tests.jsonfield_test_app.forms import JSONTestForm
+
 
 class JSONFormFieldTest(DjangoTestCase):
     def test_form_field_clean_empty_object(self):
         field = JSONFormField(required=False)
         self.assertEqual({}, field.clean('{}'))
-        
+
     def test_form_field_clean_object(self):
         field = JSONFormField(required=False)
         self.assertEqual(
-            {'foo':'bar', 'baz':2},
+            {'foo': 'bar', 'baz': 2},
             field.clean('{"foo":"bar","baz":2}')
         )
-    
+
+    def test_form_field_widget(self):
+        field = JSONFormField(required=False)
+        self.assertIn(
+            '{\n  "a": true\n}',
+            field.widget.render('json', {"a": True})
+        )
+
     def test_form_field_clean_empty_array(self):
         field = JSONFormField(required=False)
-        self.assertEqual([],field.clean('[]'))
-    
+        self.assertEqual([], field.clean('[]'))
+
     def test_required_form_field_array(self):
         field = JSONFormField(required=True)
         self.assertEqual([], field.clean('[]'))
-        
+
     def test_required_form_field_object(self):
         field = JSONFormField(required=True)
         self.assertEqual({}, field.clean('{}'))
-    
+
     def test_required_form_field_empty(self):
         field = JSONFormField(required=True)
         with self.assertRaises(ValidationError):
             field.clean('')
-    
+
     def test_invalid_json(self):
         field = JSONFormField(required=True)
-        
+
         with self.assertRaises(ValidationError):
             field.clean('{"foo"}')
 
+
 class JSONFormTest(DjangoTestCase):
     def test_form_clean(self):
         form = JSONTestForm({})
         self.assertFalse(form.is_valid())
-    
+
 
 class JSONFormMultipleSelectFieldTest(DjangoTestCase):
     def test_multiple_select_data(self):
         form = JSONTestForm({'json_data': ['SA', 'WA']})
         assert form.is_valid()
-        
-        self.assertEqual(['SA', 'WA'], form.cleaned_data['json_data'])
-
 
+        self.assertEqual(['SA', 'WA'], form.cleaned_data['json_data'])
diff --git a/jsonfield/utils.py b/jsonfield/utils.py
index 3ffca82..a6b1c6e 100644
--- a/jsonfield/utils.py
+++ b/jsonfield/utils.py
@@ -3,12 +3,14 @@ from decimal import Decimal
 
 from django.core.serializers.json import DjangoJSONEncoder
 
+
 class TZAwareJSONEncoder(DjangoJSONEncoder):
     def default(self, obj):
         if isinstance(obj, datetime.datetime):
             return obj.strftime("%Y-%m-%d %H:%M:%S%z")
         return super(TZAwareJSONEncoder, self).default(obj)
 
+
 def default(o):
     if hasattr(o, 'to_json'):
         return o.to_json()
@@ -24,5 +26,7 @@ def default(o):
         if o.tzinfo:
             return o.strftime('%H:%M:%S%z')
         return o.strftime("%H:%M:%S")
-    
+    if isinstance(o, set):
+        return list(o)
+
     raise TypeError(repr(o) + " is not JSON serializable")
diff --git a/jsonfield/widgets.py b/jsonfield/widgets.py
index 52d6116..71fe446 100644
--- a/jsonfield/widgets.py
+++ b/jsonfield/widgets.py
@@ -1,15 +1,16 @@
-import json 
+import json
 
 from django import forms
-from django.conf import settings
+from django.utils import six
 
 from .utils import default
 
+
 class JSONWidget(forms.Textarea):
     def render(self, name, value, attrs=None):
         if value is None:
             value = ""
-        if not isinstance(value, basestring):
+        if not isinstance(value, six.string_types):
             value = json.dumps(value, indent=2, default=default)
         return super(JSONWidget, self).render(name, value, attrs)
 
diff --git a/setup.py b/setup.py
index fd4dec4..e1ccdee 100644
--- a/setup.py
+++ b/setup.py
@@ -14,6 +14,7 @@ setup(
     ],
     classifiers = [
         'Programming Language :: Python',
+        'Programming Language :: Python :: 3',
         'License :: OSI Approved :: BSD License',
         'Operating System :: OS Independent',
         'Framework :: Django',
diff --git a/tests.py b/tests.py
index a698545..b5d9b16 100644
--- a/tests.py
+++ b/tests.py
@@ -1,12 +1,11 @@
 import os
 import sys
-import unittest
-import doctest
 import django
 
 BASE_PATH = os.path.dirname(__file__)
 
-def main(db_engine='sqlite3'):
+
+def main():
     """
     Standalone django model test with a 'memory-only-django-installation'.
     You can play with a django model without a complete django app installation.
@@ -22,30 +21,29 @@ def main(db_engine='sqlite3'):
     )
     global_settings.DATABASES = {
         'default': {
-            'ENGINE': 'django.db.backends.%s' % db_engine,
-            'NAME': 'django-jsonfield',
+            'ENGINE': 'django.db.backends.{DB_ENGINE}'.format(**os.environ),
+            'NAME': 'jsonfield-{DB_NAME}'.format(**os.environ),
+            'USER': os.environ.get('DB_USER', ''),
+            'PASSWORD': os.environ.get('DB_PASSWORD', ''),
         }
-    } 
+    }
 
     global_settings.STATIC_URL = "/static/"
     global_settings.MEDIA_ROOT = os.path.join(BASE_PATH, 'static')
     global_settings.STATIC_ROOT = global_settings.MEDIA_ROOT
-    
+
     global_settings.SECRET_KEY = '334ebe58-a77d-4321-9d01-a7d2cb8d3eea'
     from django.test.utils import get_runner
     test_runner = get_runner(global_settings)
 
     test_runner = test_runner()
-    
+
     if getattr(django, 'setup', None):
         django.setup()
-    
+
     failures = test_runner.run_tests(['jsonfield'])
-    
-    sys.exit(failures)
 
-def test_postgres():
-    main('postgresql_psycopg2')
+    sys.exit(failures)
 
 if __name__ == '__main__':
     main()

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-django-jsonfield.git



More information about the Python-modules-commits mailing list