From: Stephen Burrows Date: Fri, 14 Jan 2011 19:58:53 +0000 (-0500) Subject: Added fix_init_kwarg method to JSONField and connected it to the pre_init signal... X-Git-Tag: philo-0.9~22^2~10 X-Git-Url: http://git.ithinksw.org/philo.git/commitdiff_plain/4d7f6c42629cb85f001306195c6098b4abec642a Added fix_init_kwarg method to JSONField and connected it to the pre_init signal during contribute_to_class - this effectively mimics what django does for RelatedObject fields in Model.__init__ by allowing a python value to be passed in to the constructor (e.g. JSONValue(value={}) instead of JSONValue(value_json='{}')). This resolves issue 68. --- diff --git a/models/base.py b/models/base.py index c7b1c26..fae385a 100644 --- a/models/base.py +++ b/models/base.py @@ -2,8 +2,9 @@ from django import forms from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic -from django.utils import simplejson as json from django.core.exceptions import ObjectDoesNotExist +from django.utils import simplejson as json +from django.utils.encoding import smart_str from philo.exceptions import AncestorDoesNotExist from philo.models.fields import JSONField from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter @@ -73,7 +74,7 @@ class JSONValue(AttributeValue): value = JSONField() #verbose_name='Value (JSON)', help_text='This value must be valid JSON.') def __unicode__(self): - return self.value_json + return smart_str(self.value) def value_formfield(self, **kwargs): kwargs['initial'] = self.value_json diff --git a/models/fields.py b/models/fields.py index 19a6006..83798c4 100644 --- a/models/fields.py +++ b/models/fields.py @@ -243,6 +243,11 @@ class JSONField(models.TextField): def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) + models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) + + def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): + if self.name in kwargs: + kwargs[self.attname] = json.dumps(kwargs.pop(self.name)) def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField