[英]Getting 403 Forbidden error even after providing csrf token
以下是我的Ajax POST請求
這是在模板上
<script type="text/javascript">
function submit_vote(){
callback = function(data){
alert(data.message);
};
$.post("{{request.get_full_path}}vote",{
"rating" : $('#{{hash_id}}').raty('score')
}, callback, "json");
}
</script>
<div class="rating" id="{{hash_id}}" onclick="submit_vote()"></div>
在視圖上,就在這里
這是呈現存在Ajax腳本的模板的視圖
@csrf_protect
def show_rating(request, **kwargs):
....
....
return render_to_response("rating.html",
context,
context_instance = RequestContext(request))
這是采用POST請求的視圖
@login_required
@csrf_protect
def submit_vote(request, **kwargs):
if not request.method == "POST":
raise Http404
...
...
data = {"error" : False, "message" : "Thanks"}
data = simplejson.dumps(data)
return HttpResponse(data, mimetype="application/javascript")
嘗試上面的代碼后,我得到403禁止錯誤。通過使用django文檔,我向現有代碼中添加了另一個腳本(位於頂部)
<script type="text/javascript">
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>
現在我得到
Uncaught ReferenceError: csrftoken is not defined
錯誤..
如何解決? 實際上,我不了解Ajax,Jquery和JS ..只是試圖從網絡教程中構建一個簡單的請求!
您可以只在帖子請求中發送一個csrfmiddlewaretoken
,它應該是固定的。
$.post("{{request.get_full_path}}vote",{
"rating" : $('#{{hash_id}}').raty('score'),
"csrfmiddlewaretoken": {{csrf_token}},
}, callback, "json");
您不需要任何其他腳本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.