django检索csrf令牌

时间:2019-05-06 15:44:40

标签: python django

在我的Web应用程序中,我需要检索csrf令牌以通过xmlhttprequest发送一些数据,但是在服务器上,我在process_response中的第26行的“ django \ middleware \ clickjacking.py”处收到错误消息     如果response.get('X-Frame-Options')不是None: AttributeError:'str'对象没有属性'get'“。这是我的代码

// views.py

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template.context_processors import csrf

def interfacePage(request):
    return render(request, "interfacePage.html", {})

def interfacePageSubmit(request):
    if request.method == 'POST':
        datarecvd = request.POST['data']
        return render(request, "interfacePageSubmit.html", {})
    else:
        print("in def interfacePageSubmit")
        csrf1 = str(csrf(request)['csrf_token'])
        return csrf1

// interfacePage.html

function sumbit() {

        var xhr = new XMLHttpRequest();
        var url = {% url 'interfacePageSubmit' %};


        xhr.open("GET", url, false);
        xhr.withCredentials = false;
        xhr.setRequestHeader("x-csrf-token", "fetch");    
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        var data = null;
        xhr.send(data);
        console.log(xhr.readyState);
        console.log(xhr.status);

        if (xhr.readyState === 4 && xhr.status === 200) {
            var csrfToken = xhr.getResponseHeader('x-csrf-token');
            url = {% url 'interfacePageSubmit' %};
            xhr.open("POST", url, true);
            xhr.withCredentials = false;
            xhr.setRequestHeader("Accept", "application/json");
            xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            xhr.setRequestHeader('x-csrf-token', csrfToken); 
        }

**/ further code goes here

请注意,我的“ interfacePage.html ”仅包含一个没有任何表单标签的按钮

1 个答案:

答案 0 :(得分:1)

您需要返回一个HttpResponse。尝试这样的事情:

def interfacePageSubmit(request):
    # . . . 
    csrf1 = str(csrf(request)['csrf_token'])
    json_data = json.dumps(csrf1)
    return HttpResponse(json_data, content_type='json')