Issue
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
I was looking for the same thing and found this post, where they use the pygments module: https://daniel.feldroy.com/posts/pretty-formatting-json-django-admin
import json
from django.contrib import admin
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import HtmlFormatter
from django.utils.safestring import mark_safe
class YourModelAdmin(admin.ModelAdmin):
def pretty_json(self, instance):
"""Function to display pretty version of our data"""
# Convert the data to sorted, indented JSON
response = json.dumps(instance.metadata, sort_keys=True, indent=2) # <-- your field here
# Truncate the data. Alter as needed
response = response[:5000]
# Get the Pygments formatter
formatter = HtmlFormatter(style='colorful')
# Highlight the data
response = highlight(response, JsonLexer(), formatter)
# Get the stylesheet
style = "<style>" + formatter.get_style_defs() + "</style><br>"
# Safe the output
return mark_safe(style + response)
pretty_json.short_description = 'Pretty json'
Answered By - Saigesp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.