在Django中删除jsTree的所选节点的所有子节点

时间:2016-04-01 04:44:49

标签: javascript django jstree

我正在尝试删除jsTree中的节点,但遇到的问题是,刷新页面时,已删除节点的子节点仍然保存但不再有父节点,树将不会加载结果会返回错误。

当删除所选节点时,我需要一种删除与所选节点关联的所有子节点的方法,以便我不会收到此错误。

目前我已经想出了如何删除被删除的所选节点下一层的子节点,但是无法弄清楚如何删除多层子节点。

这是我的javascript,如果这还不足以帮我解决问题,请告诉我,我会发布更多相关代码:

$(function () {
    $('#jstree_demo').jstree({
            "core" : {
                "animation" : 0,
                "check_callback" : true,
                "themes" : { "stripes" : true },
                'data' : {
                  "url" : "/snippets/",
                  "success": function(data){
                     series = data;
            },
                  "dataType" : "json" // needed only if you do not supply JSON headers
                }
            },

            "plugins" : [ "contextmenu", "dnd", "search", "state", "types", "wholerow" ]
        });
});

function demo_delete() {
    var ref = $('#jstree_demo').jstree(true),
        //actual node being deleted
        sel = ref.get_selected();
    if(!sel.length) { return false; }
    // deletes one tier below selected
    selNode = ref.get_node(sel);
    ref.delete_node(selNode.children)
    //deletes selected
    ref.delete_node(sel);

};

$('#jstree_demo').on('delete_node.jstree', function (e, data) {
    console.log('something was deleted')
    var new_node = {
        'id': data.node.id,
        'parent': data.node.parent,
        'text': data.node.text
    }
    var somethingElse = JSON.stringify(new_node);

    $.ajax({
      url:'/snippets/' + data.node.id,
      type:"DELETE",
      contentType:"application/json; charset=utf-8",
      dataType:"json",

    })
})

感谢您的帮助。如果有澄清问题,请告诉我,我会及时回复。

编辑: 型号:

from django.db import models
class StoringJSON(models.Model):
  id = models.TextField(primary_key='true', default='1')
  parent = models.ForeignKey('self', verbose_name=u'Parent', null=True, blank=True, related_name='children')
  text = models.CharField(max_length=30, default='Node')

查看:

@api_view(['GET', 'PUT', 'DELETE'])
def tree_detail(request, pk):
    """
    Retrieve, update or delete a tree instance.
    """
    try:
        tree = StoringJSON.objects.get(pk=pk)
    except StoringJSON.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = TreeSerializer(tree)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = TreeSerializer(tree, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        tree.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

我想我可能必须实例化第一个对象才能启动但我不确定如何。

0 个答案:

没有答案