我目前在django中有一个模板,其中jsTree插件可以在用户与提供的数据交互时更新/保存JSON数据。
我无法弄清楚如何将这些数据保存到我的数据库中,以便用户返回他们返回此页面时所做的相同JSON数据/更改。
以下是我在模板中运行的代码。 Javascript包含在同一个文件中,以便于查看。
{% extends "testapp/base.html" %}
{% block body_block %}
<div class="container">
<div class="row">
<h3>demo</h3>
<div class="col-md-4 col-sm-8 col-xs-8">
<button type="button" onclick="demo_create();">Create</button>
<button type="button" onclick="demo_rename();">Rename</button>
<button type="button" onclick="demo_delete();">Delete</button>
<button type="button" onclick="save_changes();">Save Changes</button>
</div>
</div>
<div class="row">
<div id="jstree_demo" class="demo" style="margin-top:1em; min-height:200px;">
</div>
</div>
</div>
<!-- This should probably be moved to another JS file at some point -->
<script>
var testData = ["Child 1", { "id" : "demo_child_1", "text" : "Child 2", "children" : [ { "id" : "demo_child_2", "text" : "One more", "type" : "file" }] }];
function save_changes(){
var updatedJSON = get_tree();
}
function get_tree(){
var v = $('#jstree_demo').jstree(true).get_json('#', {flat:true})
var mytext = JSON.stringify(v);
console.log ("Updated Json:");
console.log(mytext);
return mytext;
}
function demo_create() {
var ref = $('#jstree_demo').jstree(true),
sel = ref.get_selected();
if(!sel.length) { return false; }
sel = sel[0];
sel = ref.create_node(sel, {"type":"default"});
if(sel) {
ref.edit(sel);
}
console.log("Tree created:");
console.log(testData);
get_tree();
};
function demo_rename() {
var ref = $('#jstree_demo').jstree(true),
sel = ref.get_selected();
if(!sel.length) { return false; }
sel = sel[0];
ref.edit(sel);
console.log("Renaming:");
console.log(testData);
get_tree();
};
function demo_delete() {
var ref = $('#jstree_demo').jstree(true),
sel = ref.get_selected();
if(!sel.length) { return false; }
ref.delete_node(sel);
console.log("Deleting:");
console.log(testData);
get_tree();
};
$(function () {
var to = false;
$('#demo_q').keyup(function () {
if(to) { clearTimeout(to); }
to = setTimeout(function () {
var v = $('#demo_q').val();
$('#jstree_demo').jstree(true).search(v);
}, 250);
});
$('#jstree_demo')
.jstree({
"core" : {
"animation" : 0,
"check_callback" : true,
"themes" : { "stripes" : true },
'data' : testData
},
"plugins" : [ "contextmenu", "dnd", "search", "state", "types", "wholerow" ]
});
});
</script>
{% endblock %}
我发现了django-jsonfield,我认为应该让这个过程更加简单 https://github.com/bradjasper/django-jsonfield
但是,在实现文档中指定的下面的模型之后,我不确定如何从带有视图的模板传入JSON数据并将其保存到数据库中。
from django.db import models
from jsonfield import JSONField
class MyModel(models.Model):
json = JSONField()
感谢您的帮助。