删除功能选择CSRF值作为路径

时间:2011-07-14 10:16:13

标签: jquery python ajax django

对于大量的代码感到抱歉,但我想把所有相关内容放在那里。修复可能很容易。

我正在使用filemanager应用程序django-fileman而我正在努力让它工作。所以问题是转移到删除和删除功能。但是我会在这里显示删除功能,因为它们可能有相同的问题并且功能非常相似。在应用程序中,您可以选择一组文件,然后单击“删除”,它应该删除所有选定的文件。

我将django csrf文档中的代码粘贴到我的script.js文档就绪部分。它使我的复制/剪切功能工作,但不是删除。仍然将csrf值作为路径。

问题:为什么它仍然会获取csrf值?我怎样才能以最简单的方式解决这个问题? (使用Django 1.3,但如果有问题,仍然使用csrfResponseMMiddleware

我让应用程序完全正常运行。但我必须将csrf_exempt添加到函数以及列出文件的函数中。像这样:

views.py

@permission_required('fileman.can_fm_list')
@rightPath(True)
@csrf_exempt
def ls(request, path=None):
    """ Render file list """
    path = toString(path)
    dirlist = []
    filelist = []
    for f in os.listdir(path):
        f = toString(f)
        file = File(f, "%s/%s" % (path, f))
        if os.path.isdir(os.path.join(path, f)):
            file.isdir = 1
            file.size = "Dir"
            dirlist.append(file)
        else:
            file.isdir = 0
            file.size = os.path.getsize(os.path.join(path, f))
            filelist.append(file)
        dirlist.sort()
        filelist.sort()

    buffer = listBuffer(request)
    for item in buffer:
        item.append(os.path.basename(item[0]))

    anonymous = False
    return render_to_response('list.html',
           {"pwd": path,
            "dirlist": dirlist,
            "filelist": filelist,
            "buffer": buffer,
            "anonymous": anonymous,
            "availableSpace": availableSpace(path),
        "forbiddenFolder": os.path.basename(path),
            },
            context_instance=RequestContext(request))




Deletes a set of chosen files or folders.
@permission_required('fileman.can_fm_destruct')
@csrf_exempt
def destraction2(request):
    if request.POST:
        if request.GET.has_key('next'):
        next = request.GET['next']
    else:
        next = ''
    for key in request.POST.keys():
        try:
            fmoper.remove(request.POST[key])
        except Exception, msg:
            return raise_error(request, [str(msg)])
        if request.is_ajax():
            return json({"status": "success"})
        return HttpResponseRedirect('/fm/list/%s' % next)
    else:
        return raise_error(request,
            [_(u"Empty form.")])

fmoper.remove

def remove(path):
    if os.path.isdir(path):
        return shutil.rmtree(path)
    else:
        return os.remove(path)

的script.js

script.js (Code related to a delete function of files or folders)


function destButton(element, path){
    element.html('<a href="#" ' +
    'onclick="return dest_one(this, \''+nameFromPath(path)+'\', ' +
    '\''+path+'\');" title="'+gettext("Destroy")+'">' +
    '<img src="'+url_media+'/deletered.png"WIDTH=18 HEIGHT=18        alt="'+gettext("Destroy")+'">     </a>');
    return 0;
}

...

function dest(){
    if(confirm(gettext("Huomio! Operaatiota ei voi peruuttaa! \nOletko varma että     haluat    poistaa pysyvästi valitut?"))){
    $("#fileListForm").attr("action", url_destraction+"?next="+pwd);
    $("#fileListForm").submit();
}
    return 0;
}

...


function onSuccessRemove(data){
    if(data.status=="success"){
    currentE.fadeOut("slow", function(){
    currentE.remove();
    });
}
else {
    alert(gettext("Error.\nServer reports:\n")+data.msg);
}
    return 0;
}

...
# The document ready

// Ready!
$(document).ready(function(){
    $("#filelist > tbody > tr:nth-child(odd)").addClass("odd");
    $("#filelist > tbody > tr > td > .dir").each(function(){
    $(this).dblclick(function(){
    window.location=url_home+pwd+"/"+$(this).text();
});
});
$("#filelist > tbody > tr > td > .file").each(function(){
    $(this).dblclick(function(){
        window.location=url_view+pwd+"/"+$(this).text();
    });
});

$('.block > h2').each(function(){ $(this).click(function(){
    $('.block > .content').hide();
    $(this).parent().children(".content").toggle();
}); });

$("#filelist > tbody > tr > td > .file").each(function(){
    $(this).attr("onclick", 'fileClick($(this).text())');
});
$("#download").hide();
$("#clipboard").hide();
$.clipboardReady(function(){}, { swfpath: url_media+"/jquery.clipboard.swf" });

// Copied from django documentation

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                 }
               }
             }
             return cookieValue;
           }
           function sameOrigin(url) {
               // url could be relative or scheme relative or absolute
               var host = document.location.host; // host + port
               var protocol = document.location.protocol;
               var sr_origin = '//' + host;
               var origin = protocol + sr_origin;
               // Allow absolute or scheme relative URLs to same origin
               return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                   (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                   // or any other URL that isn't scheme relative or absolute i.e relative.
                   !(/^(\/\/|http:|https:).*/.test(url));
           }
           function safeMethod(method) {
               return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
           }

if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

});

1 个答案:

答案 0 :(得分:1)

以下代码处理csrf令牌cookie时可能不足为奇:

if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

尝试使用您自己的Cookie名称,如果您需要请求标题,请使用您自己的名称。