(`json.dumps` with `indent`)
--
Ticket URL: <https://code.djangoproject.com/ticket/26482>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* needs_better_patch: => 0
* needs_tests: => 0
* needs_docs: => 0
Comment:
I'm not convinced this belongs in the form field. I think such logic
belongs in a custom widget.
--
Ticket URL: <https://code.djangoproject.com/ticket/26482#comment:1>
Comment (by davidszotten):
ah, that's a good suggestion
--
Ticket URL: <https://code.djangoproject.com/ticket/26482#comment:2>
Comment (by davidszotten):
that solves my problem so happy to close, unless you think such a widget
would make sense to include? (maybe to niche)
--
Ticket URL: <https://code.djangoproject.com/ticket/26482#comment:3>
* status: new => closed
* resolution: => wontfix
Comment:
I agree.
--
Ticket URL: <https://code.djangoproject.com/ticket/26482#comment:4>
--
Ticket URL: <https://code.djangoproject.com/ticket/26482#comment:5>
Comment (by minusf):
I would normally agree with a custom widget approach, however `json` is
special.
In my understanding a custom widget would have to munge through the
vanilla unindented
`json.dumps()` value returned by
`contrib.postgres.forms.JSONField.prepare_value()`.
`django/contrib/postgres/forms/jsonb.py:`
{{{
def prepare_value(self, value):
if isinstance(value, InvalidJSONInput):
return value
return json.dumps(value)
}}}
Probably meaning an ugly hack of `json.loads()` then `json.dumps()` round
trip inside the custom widget...
For my use cases a simple `json.dumps(value, indent=2)` would already make
a huge difference in readability, no custom widget needed and problem
solved.
Overriding that however is a mess...
`models.py`:
{{{
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.forms import JSONField as JSONFormField
from django.core.serializers.json import DjangoJSONEncoder
# XXX not exported from postgres.forms :/
class InvalidJSONInput(str):
pass
# XXX JSONFormField would be a better name for forms.JSONField :/
class IndentedJSONFormField(JSONFormField):
def prepare_value(self, value):
if isinstance(value, InvalidJSONInput):
return value
return json.dumps(value, indent=2)
class IndentedJSONField(JSONField):
def formfield(self, **kwargs):
return super().formfield(**{
'form_class': IndentedJSONFormField,
**kwargs,
})
class Data(models.Model):
data = IndentedJSONField(encoder=DjangoJSONEncoder, default=dict)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/26482#comment:6>