gpt4 book ai didi

django - JsonEditor 与 Django Admin 集成

转载 作者:行者123 更新时间:2023-12-01 23:43:29 25 4
gpt4 key购买 nike

我正在努力集成JSONEditor进入 Django 管理员。我的模型中有一个字段使用 Postgres JSON,并且该库中的树编辑器非常完美。

模型.py
class Executable(models.Model):
""" Simplified model for sake of the question."""

recipe = JSONField(null=True, blank=True)

我已经取得了不错的进展(我认为),将 JSONEditor 库集成到 Django 管理中适当的创建/编辑屏幕中。数据在加载时显示正确,但由于某种原因,当我在 JSONEditorWidget 中进行编辑时,更改不会保存。我确信我需要处理一些 save 覆盖,或者我遗漏了一些明显的东西,但我真的不知道从这里该去哪里。

admin.py
import json
from django import forms, utils
from django.contrib import admin

from .models import Executable


class JSONEditorWidget(forms.Widget):
html_template = """
<div id='%(name)s_editor_holder'></div>
<script type="text/javascript">
var options = {
"mode": "tree",
"search": true
};
var %(name)s_editor = new JSONEditor(container, options);
var json = %(value)s
%(name)s_editor.set(json);
%(name)s_editor.expandAll();

var json = %(name)s_editor.get(json);
</script>
<textarea readonly class="vLargeTextField" cols="40" id="id_%(name)s" name="%(name)s" rows="2" height="20px">%(value)s</textarea>
"""
def __init__(self, attrs=None, formats=None, defaults=None):
self.formats = formats
self.defaults = defaults
super(JSONEditorWidget, self).__init__(attrs)

def render(self, name, value, attrs=None):
if isinstance(value, basestring): # Edit existing instance
value = json.loads(value)
result = self.html_template % {
'name': name,
'value': json.dumps(value)
}
return utils.safestring.mark_safe(result)


class ExecutableForm(forms.ModelForm):
recipe = forms.CharField(widget=JSONEditorWidget()) # Kwargs here?

class Meta:
model = Executable
fields = '__all__'

class Media:
css = {
'all': ('http://www.jsoneditoronline.org/app.min.css',) # TEMP
}
js = (
'http://www.jsoneditoronline.org/app.min.js', # TEMP
)


class ExecutableAdmin(admin.ModelAdmin):
model = Executable
form = ExecutableForm
fields = (('request', 'status'), 'recipe')


admin.site.register(Executable, ExecutableAdmin)

最佳答案

我的 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.

关于django - JsonEditor 与 Django Admin 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37535618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com