65 lines
2.2 KiB
Python
65 lines
2.2 KiB
Python
# zoo - versatile objects management
|
|
# Copyright (C) 2016 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
import json
|
|
|
|
from django.utils.safestring import mark_safe
|
|
from django import forms
|
|
|
|
|
|
class JSONEditor(forms.Textarea):
|
|
def __init__(self, *args, **kwargs):
|
|
self.schema = kwargs.pop('schema', None)
|
|
super(JSONEditor, self).__init__(*args, **kwargs)
|
|
|
|
def render(self, name, value, attrs=None, renderer=None):
|
|
default_schema = {
|
|
'type': 'object',
|
|
'additionalProperties': True,
|
|
}
|
|
attrs['style'] = 'display: none'
|
|
s = super(JSONEditor, self).render(name, value, attrs=attrs, renderer=renderer)
|
|
s += mark_safe(
|
|
'<div style="display: inline-block; width: 80%%" id="%s_editor_holder"></div>"'
|
|
% attrs['id'])
|
|
s += mark_safe('''<script>
|
|
(function () {
|
|
var schema = %(schema)s;
|
|
JSONEditor.defaults.editors.object.options.collapsed = true;
|
|
var jsoneditor = new JSONEditor(document.getElementById("%(id)s_editor_holder"),
|
|
{
|
|
theme: "foundation",
|
|
schema: schema,
|
|
show_errors: "always",
|
|
});
|
|
var input = document.getElementById("%(id)s");
|
|
var content = document.getElementById("%(id)s").value;
|
|
jsoneditor.on('change', function () {
|
|
input.value = JSON.stringify(jsoneditor.getValue());
|
|
})
|
|
if (content) {
|
|
jsoneditor.setValue(JSON.parse(content));
|
|
}
|
|
})();
|
|
</script>''' % {
|
|
'schema': json.dumps(self.schema or default_schema),
|
|
'id': attrs['id'],
|
|
})
|
|
return s
|
|
|
|
class Media:
|
|
js = ('js/jsoneditor.min.js',)
|