/django-json-widget

An alternative widget that makes it easy to edit the new Django's field JSONField (PostgreSQL specific model fields)

Primary LanguagePythonMIT LicenseMIT

django-json-widget

https://travis-ci.org/jmrivas86/django-json-widget.svg?branch=master

An alternative widget that makes it easy to edit the new Django's field JSONField (PostgreSQL specific model fields)

Quickstart

Install django-json-widget:

pip install django-json-widget

Add it to your INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'django_json_widget',
    ...
)

Add to your settings.py:

JSON_EDITOR_JS = 'https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.0.3/jsoneditor.js'
JSON_EDITOR_CSS = 'https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.0.3/jsoneditor.css'

Add the widget in your admin.py:

from django.contrib import admin
# from django.contrib.postgres import fields # if django < 3.1
from django.db import models
from django_json_widget.widgets import JSONEditorWidget
from .models import YourModel


@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        # fields.JSONField: {'widget': JSONEditorWidget}, # if django < 3.1
        models.JSONField: {'widget': JSONEditorWidget},
    }

You can also add the widget in your forms.py:

from django import forms
from django_json_widget.widgets import JSONEditorWidget
from .models import YourModel


class YourForm(forms.ModelForm):
    class Meta:
        model = YourModel

        fields = ('jsonfield',)

        widgets = {
            'jsonfield': JSONEditorWidget
        }

Configuration

You can customize the JSONEditorWidget with the following options:

  • width: Width of the editor as a string with CSS size units (px, em, % etc). Defaults to 90%.
  • height: Height of the editor as a string CSS size units. Defaults to 550px.
  • options: A dict of options accepted by the JSON editor. Options that require functions (eg. onError) are not supported.
  • mode (deprecated): The default editor mode. This argument is redundant because it can be specified as a part of options. Preserved for backwards compatibility with version 0.2.0.
  • attrs: HTML attributes to be applied to the wrapper element. See the Django Widget documentation.

JSONEditorWidget widget

Before:

https://raw.githubusercontent.com/jmrivas86/django-json-widget/master/imgs/jsonfield_0.png

After:

https://raw.githubusercontent.com/jmrivas86/django-json-widget/master/imgs/jsonfield_1.png

Credits

Tools used in rendering this package: