#26482: pretty-print json in JSONField form field
----------------------------------+--------------------------------------
Reporter: David Szotten | Owner: (none)
Type: New feature | Status: closed
Component: contrib.postgres | Version: master
Severity: Normal | Resolution: wontfix
Keywords: | Triage Stage: Unreviewed
Has patch: 1 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
----------------------------------+--------------------------------------
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>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/070.7b006250dc6f623137c4bf862289fcea%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.