DWQA QuestionsCategory: ProgramCsrftoken error in Django + Ajax + Post?
kjhlafa asked 2 months ago

This is the official document I checked
Why do CSRF errors occur? I added CSRF to the data parameter?

    Forbidden (CSRF token missing or incorrect.): /account/test/
    [20/Oct/2016 18:10:44] "POST /account/test/ HTTP/1.1" 403 2274

Ajax code var csrftoken = cookies. Get (‘csrftoken ‘); It’s weird here

function doTest() {
        //This is written according to the official document. It's not very clear. If you add this sentence, the post form will not be submitted at all
        //var csrftoken = Cookies.get('csrftoken');
            type: "POST",
            url: "/account/test/",
            //There may be a problem here, but CSRF is used, so JSON. Stringify() is not called,
            //What should I do here?
            data: {name: 'john', csrfmiddlewaretoken: '{{ csrf_token  }}'},
            contentType : 'application/json; charset=utf-8',
            dataType: "json",
            success: function(json) {

Django code

def diff_response(request):
    if request.method == 'POST':
        # data = json.loads(request.body.decode('utf-8'))
        # print data['name']
        print request.body
    json_data = [{'name': 'tom', 'id': '1'},
                 {'name': 'mike', 'id': '2'}]
    return HttpResponse(json.dumps(json_data, ensure_ascii=False))

Call Ajax

<input type="submit" id="test-json" onclick="doTest()" value="test-json"/>
piperck replied 2 months ago

If I remember correctly by checking the official documents, a middleware enabled by Django by default will block risky Ajax requests

piperck replied 2 months ago

Looking at it, another weird thing is if I add it in the Ajax section
var csrftoken = Cookies.get('csrftoken');
In this sentence, it doesn’t report anything wrong, but it doesn’t see its submission form in the background. Without this sentence, the form can still be submitted, but there will be 403csrf errors.

piperck replied 2 months ago

This is why Django doesn’t submit the form after adding this sentence. I use 1.98

2 Answers
flyingpang answered 2 months ago

Try adding a decorator to the view again.

from django.views.decorators.csrf import csrf_exempt

def diff_response(request):
ztcaoll222 replied 2 months ago

Not to solve the problem, but to eliminate the problem?

Donl answered 2 months ago

How did you solve it? I’ve been looking for it all day? thank you