Harry
Harry

Reputation: 3038

django retrieve csrf token

In my web application I need to retrieve csrf token for sending some data through xmlhttprequest but I'm getting an error at the server as " django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' ". This is my code

//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

Pls note my "interfacePage.html only contains a button without any form tag

Upvotes: 0

Views: 89

Answers (1)

NS0
NS0

Reputation: 6106

You need to return an HttpResponse. Try something like this:

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

Upvotes: 1

Related Questions