Django Pretty JSON
django-prettyjson is a Django library that provides a pretty JSON viewer for Django forms, admin, and templates. It's built upon jQuery JSONView and is compatible with various JSON storage methods, including raw JSON strings, Django's `JSONField` (from `django.contrib.postgres` or `django-jsonfield`), and any Python object serializable to JSON via `standardjson`. The current version is 0.4.1, and while the last code push was 9 months ago, the last official release was in 2018, indicating a maintenance release cadence.
Common errors
-
ModuleNotFoundError: No module named 'prettyjson'
cause The 'prettyjson' app was not added to your Django project's `INSTALLED_APPS` setting.fixAdd `'prettyjson'` to the `INSTALLED_APPS` tuple in your `settings.py` file. -
TemplateSyntaxError: 'prettyjson' is not a registered tag library, or is not available in this version of Django.
cause You are trying to use the `prettyjson` template tags without loading them first in your template.fixAdd `{% load prettyjson %}` at the top of your Django template file where you intend to use the tags. -
TypeError: __init__() missing 1 required positional argument: 'token' (when defining custom template tag)
cause While not directly an error from `django-prettyjson`, a common mistake when dealing with template tags (like `prettyjson`) is incorrectly defining custom ones, leading to `TemplateSyntaxError` or `TypeError` if syntax or arguments are mishandled.fixEnsure custom template tags adhere to Django's parsing function signature (e.g., `def do_my_tag(parser, token):`) and correctly handle `token.split_contents()` and return a `Node` instance.
Warnings
- gotcha If your page already includes jQuery, `{% prettyjson_setup %}` will load `django.jQuery` to avoid conflicts. To prevent loading jQuery a second time, use `{% prettyjson_setup jquery=False %}`.
- gotcha By default, the JSON widget in forms/admin might render as a raw string with a button to parse it. To render as parsed JSON initially, you can configure the widget with `attrs={'initial': 'parsed'}`.
- gotcha The `PrettyJSONWidget` might not apply formatting to fields explicitly marked as `readonly_fields` in the Django admin. This means the JSON content will appear as plain text.
- gotcha There have been reports of backslashes being added to JSON data in `jsonfield` on repeated saves when editing a model in the admin interface (Issue #17). This can lead to corrupted JSON data.
Install
-
pip install django-prettyjson
Imports
- PrettyJSONWidget
from django_prettyjson import PrettyJSONWidget
from prettyjson import PrettyJSONWidget
Quickstart
import os
from django import forms
from django.db import models
from django.contrib import admin
from prettyjson import PrettyJSONWidget
# Add 'prettyjson' to INSTALLED_APPS in settings.py
# INSTALLED_APPS = [
# # ...
# 'prettyjson',
# ]
# Example Model with a JSONField (requires django.contrib.postgres or django-jsonfield)
class MyData(models.Model):
name = models.CharField(max_length=100)
json_data = models.JSONField(default=dict)
def __str__(self):
return self.name
# Integrate PrettyJSONWidget in Django Admin
@admin.register(MyData)
class MyDataAdmin(admin.ModelAdmin):
list_display = ('name',)
formfield_overrides = {
models.JSONField: {'widget': PrettyJSONWidget }
}
# Or for a specific field in a custom form:
class MyDataForm(forms.ModelForm):
class Meta:
model = MyData
fields = '__all__'
widgets = {
'json_data': PrettyJSONWidget()
}
# For templates, include in your Django template file:
# {% load prettyjson %}
# <head>
# {{ block.super }}
# {% prettyjson_setup %}
# </head>
# <body>
# {% prettyjson my_queryset %}
# {% prettyjson my_dict %}
# {% prettyjson '{"example": "JSON string"}' %}
# </body>