-
-
Save rgupta2/761fd987254703673d83426912dc015d to your computer and use it in GitHub Desktop.
JSON editor in admin for Django, jsoneditor, Postgres (from http://stackoverflow.com/a/40326235/2742038)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/jsoneditor.min.css',) } | |
js = ('jsoneditor/jsoneditor.min.js', ) | |
class ConsumerAdmin(admin.ModelAdmin): | |
list_display = ('id') # list of fields, e.g. 'id', that you want to be part of list_display | |
model = Consumer | |
form = ConsumerForm | |
admin.site.register(Consumer, ConsumerAdmin) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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, | |
change: function () { | |
var json = editor.get(); | |
document.getElementById("id_{{ name }}").value=JSON.stringify(json); | |
} | |
}; | |
var editor = new JSONEditor(container, options); | |
var json = {{ data|safe }}; | |
json = JSON.parse(json); // Without this step, the entire json will get treated as text | |
editor.set(json); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.postgres.fields import JSONField | |
class Consumer(models.Model): | |
data = JSONField(default={}, db_index=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment