2015-05-23 50 views
1

我遵循了很多StackOverflow推薦的東西,但無濟於事。此外,我試圖在各個地方的HTML中擠壓{%csrf_token%},但似乎沒有任何工作。有什麼建議麼?這裏是我的Django的模板輸入按鈕:儘管Firebug說cookie標籤下面有一個csrftoken,但是Django的CSRF驗證失敗。爲什麼?

<input id=saveWaypoints type=button value=Save disabled=disabled> 

然後觸發此Javascript:

$('#saveWaypoints').click(function() { 
    var waypointStrings = []; 
    for (id in waypointByID) { 
     waypoint = waypointByID[id]; 
     waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat); 
    }; 
    waypointStrings["csrfmiddlewaretoken"] = $('input[name=csrfmiddlewaretoken]').val(); 
    $.post("{% url 'waypoints-save' %}", { 
     waypointsPayload: waypointStrings.join('\n') 
    }, function (data) { 
     if (data.isOk) { 
      $('#saveWaypoints').attr('disabled', 'disabled'); 
     } else { 
      alert(data.message); 
     } 
    }); 
}); 

,然後調用views.py了這樣的觀點:

def save(request): 
    'Save waypoints' 
    for waypointString in request.POST.get('waypointsPayload', '').splitlines(): 
     waypointID, waypointX, waypointY = waypointString.split() 
     waypoint = Waypoint.objects.get(id=int(waypointID)) 
     waypoint.geometry.set_x(float(waypointX)) 
     waypoint.geometry.set_y(float(waypointY)) 
     waypoint.save() 
    return HttpResponse(simplejson.dumps(dict(isOk=1)), content_type='application/json') 

回答

4

根據Django文檔,你可以將放入令牌作爲請求的標頭將其添加爲有效負載https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax

就快,但你必須把它發送它自己的參數,而不是waypointsPayload部分:

$.post("{% url 'waypoints-save' %}", { 
    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), 
    waypointsPayload: waypointStrings.join('\n') 
}, function (data) { 
    ... 
}); 

的Cookie是代替的備用位置讀取令牌,輸入(如果您不想用令牌標記胡椒模板)。

+0

謝謝!重量已被解除。 – Sticky