Merge pull request #1174 from ostcar/json_field

Use the jsonfield as requirement
This commit is contained in:
Oskar Hahn 2014-01-11 14:42:39 -08:00
commit 5ea13deccc
10 changed files with 8 additions and 120 deletions

View File

@ -256,6 +256,9 @@ OpenSlides uses the following projects or parts of them:
* `Django haystack <http://haystacksearch.org>`_, License: BSD * `Django haystack <http://haystacksearch.org>`_, License: BSD
* `django-jsonfield <https://github.com/bradjasper/django-jsonfield>_,
License: MIT
* `pdf.js <http://mozilla.github.io/pdf.js/>`_, License: Apache License v2.0 * `pdf.js <http://mozilla.github.io/pdf.js/>`_, License: Apache License v2.0
* `Pillow <https://github.com/python-imaging/Pillow/>`_, License: Standard * `Pillow <https://github.com/python-imaging/Pillow/>`_, License: Standard

View File

@ -3,7 +3,7 @@
from django.db import models from django.db import models
from django.utils.translation import ugettext_noop from django.utils.translation import ugettext_noop
from openslides.utils.jsonfield import JSONField from jsonfield import JSONField
class ConfigStore(models.Model): class ConfigStore(models.Model):
@ -11,7 +11,7 @@ class ConfigStore(models.Model):
A model class to store all config variables in the database. A model class to store all config variables in the database.
""" """
key = models.CharField(max_length=255, primary_key=True) key = models.CharField(max_length=255, unique=True, db_index=True)
"""A string, the key of the config variable.""" """A string, the key of the config variable."""
value = JSONField() value = JSONField()

View File

@ -12,7 +12,7 @@ from openslides.mediafile.models import Mediafile
from openslides.poll.models import (BaseOption, BasePoll, BaseVote, from openslides.poll.models import (BaseOption, BasePoll, BaseVote,
CollectInvalid, CollectVotesCast) CollectInvalid, CollectVotesCast)
from openslides.projector.models import RelatedModelMixin, SlideMixin from openslides.projector.models import RelatedModelMixin, SlideMixin
from openslides.utils.jsonfield import JSONField from jsonfield import JSONField
from openslides.utils.person import PersonField from openslides.utils.person import PersonField
from .exceptions import WorkflowError from .exceptions import WorkflowError

View File

@ -1,20 +0,0 @@
Copyright (c) 2012 Brad Jasper
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,13 +0,0 @@
https://github.com/bradjasper/django-jsonfield
django-jsonfield is a reusable django field that allows you to store validated JSON in your model.
It silently takes care of serialization. To use, simple add the field to one of your models.
===
from django.db import models
from jsonfield import JSONField
class MyModel(models.Model):
json = JSONField()

View File

@ -1,3 +0,0 @@
from fields import JSONField
__all__ = ['JSONField']

View File

@ -1,79 +0,0 @@
# -*- coding: utf-8 -*-
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.forms.fields import Field
from django.forms.util import ValidationError as FormValidationError
from django.utils.translation import ugettext as _
class JSONFormField(Field):
def clean(self, value):
if not value and not self.required:
return None
value = super(JSONFormField, self).clean(value)
if isinstance(value, basestring):
try:
json.loads(value)
except ValueError:
raise FormValidationError(_("Enter valid JSON"))
return value
class JSONField(models.TextField):
"""JSONField is a generic textfield that serializes/unserializes JSON objects"""
# Used so to_python() is called
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
self.dump_kwargs = kwargs.pop('dump_kwargs', {'cls': DjangoJSONEncoder})
self.load_kwargs = kwargs.pop('load_kwargs', {})
super(JSONField, self).__init__(*args, **kwargs)
def to_python(self, value):
"""Convert string value to JSON"""
if isinstance(value, basestring):
try:
return json.loads(value, **self.load_kwargs)
except ValueError:
pass
return value
def get_db_prep_value(self, value, connection, prepared=False):
"""Convert JSON object to a string"""
if isinstance(value, basestring):
return value
return json.dumps(value, **self.dump_kwargs)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
def value_from_object(self, obj):
return json.dumps(super(JSONField, self).value_from_object(obj))
def formfield(self, **kwargs):
if "form_class" not in kwargs:
kwargs["form_class"] = JSONFormField
field = super(JSONField, self).formfield(**kwargs)
if not field.help_text:
field.help_text = "Enter valid JSON"
return field
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^jsonfield\.fields\.JSONField"])
except ImportError:
pass

View File

@ -1 +0,0 @@
# Django needs this to see it as a project

View File

@ -4,6 +4,7 @@ beautifulsoup4>=4.3,<4.4
bleach>=1.2,<1.3 bleach>=1.2,<1.3
django-haystack>=2.1,<2.2 django-haystack>=2.1,<2.2
django-mptt>=0.6,<0.7 django-mptt>=0.6,<0.7
jsonfield>=0.9,<0.10
pillow>=2.2,<2.3 pillow>=2.2,<2.3
reportlab>=2.7,<2.8 reportlab>=2.7,<2.8
sockjs-tornado>=1.0,<1.1 sockjs-tornado>=1.0,<1.1

View File

@ -179,7 +179,7 @@ class ConfigFormTest(TestCase):
self.assertEqual(config['string_var'], 'other_special_unique_string faiPaid4utie6eeL') self.assertEqual(config['string_var'], 'other_special_unique_string faiPaid4utie6eeL')
self.assertFalse(config['bool_var']) self.assertFalse(config['bool_var'])
self.assertEqual(config['integer_var'], 3) self.assertEqual(config['integer_var'], 3)
self.assertEqual(config['choices_var'], 2) self.assertEqual(config['choices_var'], '2')
def test_post_config_form_error(self): def test_post_config_form_error(self):
response = self.client_manager.post( response = self.client_manager.post(