T
T
tupoi2017-04-24 22:35:10
JavaScript
tupoi, 2017-04-24 22:35:10

How to send csrftoken to Django server?

Good day, using jquery.ajax and django, I can not send a post request, because Forbidden (CSRF token missing or incorrect.):
ajax request

<script type="text/javascript">

    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 getAjax() {
        var csrftoken = getCookie('csrftoken');
        alert(csrftoken);
        $.ajaxSetup({
            headers: {
                'X-CSRF-Token': csrftoken
            }
        });

        $.ajax({
            url: "/os/detect/",
            type: "POST",
            data: {
                os_type: "macOS"
            },
            success: function (msg) {
                alert(msg);
            },
            error: function () {
                alert("опять не получилось");
            }
        });
    }
</script>


django view

@csrf_protect
def userOS(request):
    if request.is_ajax():
        os_type = request.POST['os_type']
        AnalyzeOS.objects.create(
            os_type=os_type
        )
        return HttpResponse('OK')
    else:
        return render_to_response('os.html')


at the same time I look through the cookies, there is a csrf that came from the server, I look at my post request, csrf is also set in the header, but it still gives an error, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2017-04-24
@tupoi

https://docs.djangoproject.com/en/1.11/ref/csrf/#s
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question