我发送了令牌,但仍然收到错误:(

时间:2019-12-30 18:16:42

标签: javascript python django ajax

我通过ajax发送令牌,但仍然收到错误

  

禁止(未设置CSRF cookie):/ main / create /

мойView.py

# Create your views here.
def main(request):
    if request.method == 'POST':
        # print(str(request.POST))
        # print('I have a post!')
        markx = request.POST.get("coordx")
        marky = request.POST.get("coordy")
        markcoord.objects.create(xcord=markx, ycord=marky, city=City[0])
        list_of_marks_cord = []
        list_of_marks = []
    else:
        allmarks = markcoord.objects.all()
        list_of_marks_cord = []
        list_of_marks = []

        for mark in allmarks:

            time = mark.timecreate.replace(tzinfo=None)
            dif = datetime.datetime.utcnow() - time
            # print(dif.total_seconds() // 3600)
            if dif.total_seconds() // 3600 >= 3:
                markcoord.objects.filter(id=mark.id).delete()

            else:
                list_of_marks_cord.append([mark.xcord, mark.ycord])
                list_of_marks.append([mark.id, mark.hate_point, mark.like_point])

    return render(request, 'index.html', {'marklist': list_of_marks, 'cord_List': list_of_marks_cord})

我的main.js

var myMap;
var MyIconContentLayout;
ymaps.ready(init);
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;
}
var csrftoken = getCookie('csrftoken');


function place(coords) {
    var placemark = new ymaps.Placemark([coords[0], coords[1]],
        {iconContent: 'DPS'},
        {
            iconLayout: 'default#image',
            // iconImageClipRect: [[0,0], [26, 47]],
            iconImageHref: 'static/img/metka.svg',
            iconImageSize: [30, 30],
            iconImageOffset: [-15, -27],
        },);
    $.ajax({
        type: 'POST',
        url: '/main/create/',
        headers: {
            "X-CSRFToken": csrftoken
        },// some data url
        data: {coordx: coords[0], coordy: coords[1]},  // some params
        success: function (response) {     // callback
            if (response.result === 'OK') {
                if (response.data && typeof (response.data) === 'object') {
                    // do something with the successful response.data
                    // e.g. response.data can be a JSON object
                }
            } else {
                // handle an unsuccessful response
            }
        }
    });
...

预先感谢您的帮助!

我第一次将django上载到服务器,尽管在本地计算机上一切正常,但每次尝试摆脱csrf时,都会出现此错误,攀登坞无济于事

0 个答案:

没有答案