From db19619545dd99a1d2502c72974d79eca33acff7 Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Sat, 26 Mar 2016 20:11:57 +0100 Subject: Fixed #25532 -- Properly redisplayed JSONField form input values Thanks David Szotten for the report and Tommy Beadle for code inspiration. Thanks Tim Graham for the review. --- django/contrib/postgres/forms/jsonb.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'django/contrib/postgres/forms') diff --git a/django/contrib/postgres/forms/jsonb.py b/django/contrib/postgres/forms/jsonb.py index 8eefc14993..415288dc90 100644 --- a/django/contrib/postgres/forms/jsonb.py +++ b/django/contrib/postgres/forms/jsonb.py @@ -1,11 +1,16 @@ import json from django import forms +from django.utils import six from django.utils.translation import ugettext_lazy as _ __all__ = ['JSONField'] +class InvalidJSONInput(six.text_type): + pass + + class JSONField(forms.CharField): default_error_messages = { 'invalid': _("'%(value)s' value must be valid JSON."), @@ -27,5 +32,15 @@ class JSONField(forms.CharField): params={'value': value}, ) + def bound_data(self, data, initial): + if self.disabled: + return initial + try: + return json.loads(data) + except ValueError: + return InvalidJSONInput(data) + def prepare_value(self, value): + if isinstance(value, InvalidJSONInput): + return value return json.dumps(value) -- cgit v1.3