Django JSON Widget
Django JSON Widget provides an alternative, user-friendly widget for editing Django's JSONField, featuring syntax highlighting, automatic indentation, and validation. It leverages the JSONEditor JavaScript library to enhance the default Django form experience. The library is actively maintained, with frequent updates, and is currently at version 2.1.1.
Warnings
- deprecated The `mode` argument for `JSONEditorWidget` is deprecated since version 0.2.0. Instead, specify the editor mode (e.g., 'tree', 'code', 'form') via the `options` dictionary, which accepts arguments directly from the underlying JSON Editor JavaScript library.
- gotcha Using inline scripts in the widget might conflict with Content Security Policies (CSP) if not properly configured, potentially leading to script blocking and functionality issues.
- gotcha There are reported issues with the widget not functioning correctly or rendering improperly when used within Django's `TabularInline` or when integrated with third-party admin themes like `Grappelli`.
- breaking Prior to version 2.0.0, users experienced issues with Django 4.x due to missing sourcemaps and incorrect default paths for static files, leading to improper rendering or functionality.
Install
-
pip install django-json-widget
Imports
- JSONEditorWidget
from django_json_widget.widgets import JSONEditorWidget
Quickstart
from django.contrib import admin
from django.db import models
from django_json_widget.widgets import JSONEditorWidget
# models.py (example)
class MyModel(models.Model):
name = models.CharField(max_length=255)
data = models.JSONField(default=dict)
def __str__(self):
return self.name
# admin.py (example)
from django.contrib import admin
from .models import MyModel
from django_json_widget.widgets import JSONEditorWidget
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
list_display = ('name',)
formfield_overrides = {
models.JSONField: {'widget': JSONEditorWidget},
}
# Alternatively, in a custom form:
# from django import forms
# from .models import MyModel
# from django_json_widget.widgets import JSONEditorWidget
#
# class MyForm(forms.ModelForm):
# class Meta:
# model = MyModel
# fields = ('name', 'data')
# widgets = {
# 'data': JSONEditorWidget,
# }