1
아래 여기,이의 의견에 템플릿도 CSRF 토큰
<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>
에 내 아약스 POST 요청
입니다입니다 제공 후
이 뷰는 그 Ajax 스크립트가있는 템플릿을 렌더링합니다.
이것은 POST 요구 사항 위의 코드를 시도하면 t
@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 금지 오류 ... 무엇입니까, 나는 내가 지금 (상단) 기존 코드에 다른 스크립트
<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에 대해 알지 못한다. 단지 웹 튜토리얼을 통해 간단한 요청을 작성하려고 노력하고있다.