'Pretty print django.db.models.JSONField in Django admin?
Django >= 3.1 supports a new JSONField model field. I am using one like this:
from django.db import models
class Example(models.Model):
foobar = models.JSONField()
I've also included this model in Django's admin section. However, the field is just a simple textarea with the JSON included, not pretty printed.
How can I make sure the JSON displayed in Django's admin section is pretty printed, with indentation, like this:
{
"example": {
"a": 1,
"b": 2
}
}
Solution 1:[1]
Here is a way to indent the JSON field without additional third party packages:
import json
from django import forms
from django.contrib import admin
class PrettyJSONEncoder(json.JSONEncoder):
def __init__(self, *args, indent, sort_keys, **kwargs):
super().__init__(*args, indent=2, sort_keys=True, **kwargs)
class MyModelForm(forms.ModelForm):
json_field = forms.JSONField(encoder=PrettyJSONEncoder)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samad A |
