JsonEditor integration with Django Admin

女生的网名这么多〃 提交于 2019-11-30 07:29:17
roach

My solution for Django 1.10.2, jsoneditor#^5.5.9, Postgres 9.5:

models.py

from django.contrib.postgres.fields import JSONField

class Consumer(models.Model):
    data = JSONField(default=dict, db_index=True)

admin.py:

from django import forms
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string

from .models import Consumer


class JSONEditorWidget(forms.Widget):

    template_name = 'jsoneditor.html'

    def render(self, name, value, attrs=None):
        context = {
            'data': value,
            'name': name
        }

        return mark_safe(render_to_string(self.template_name, context))


class ConsumerForm(forms.ModelForm):

    class Meta:
        model = Consumer
        fields = '__all__'
        widgets = {
            'data': JSONEditorWidget()
        }

    class Media:
        css = { 'all': ('jsoneditor/dist/jsoneditor.min.css',) }
        js = ('jsoneditor/dist/jsoneditor.min.js', )


class ConsumerAdmin(admin.ModelAdmin):
    list_display = ['pk']
    model = Consumer
    form = ConsumerForm

admin.site.register(Consumer, ConsumerAdmin)

jsoneditor.html:

<div id="{{ name }}_editor"></div>

<textarea cols="40" id="id_{{ name }}" name="{{ name }}" rows="10" required="" style="display: none">{{ data }}</textarea>


<script>
    console.log('jsoneditor.html');
    var container = document.getElementById("{{ name }}_editor");

    var options = {
        modes: ['code', 'tree'],
        search: true,

        onChange: function () {
            var json = editor.get();
            document.getElementById("id_{{ name }}").value=JSON.stringify(json);
        }
    };

    var editor = new JSONEditor(container, options);
    var json = {{ data|safe }};
    editor.set(json);
</script>

Blockquote Written with StackEdit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!