[英]Why am I getting a 403 Forbidden error in Django when I do a POST request with AJAX?
In Django Console I'm getting this message in red: 在Django控制台中,我得到的消息是红色的:
[16/Jan/2015 01:33:34] "POST /accounts/benjamin/listview HTTP/1.1" 404 7562
In Chrome Dev Console, I'm getting this error: 在Chrome开发者控制台中,出现此错误:
jquery-2.1.1.min.js:4 POST http://127.0.0.1:8000/accounts/benjamin/listview/ 403 (FORBIDDEN)
jquery-2.1.1.min.js:4 k.cors.a.crossDomain.send
Here is my view method: (note, I just now added @ensure_csrf_cookie after reading other SO posts, but this did not resolve the issue) 这是我的视图方法:(注意,我刚刚在阅读其他SO帖子后添加了@ensure_csrf_cookie,但这不能解决问题)
@ensure_csrf_cookie
def delete_object(request):
if request.is_ajax():
print "request is ajax"
object_name = request.POST.get('entryname')
targetobject = Entry.objects.get(headline=object_name)
if request.user.username == targetobject.author:
targetobject.delete()
print "hello"
return HttpResponseRedirect('/storefront/')
And AJAX code in the template: 以及模板中的AJAX代码:
<script type="text/javascript">
var my_app = {
username: "{{ request.user.username }}"
};
</script>
<script>
$(document).ready(function() {
$(".delete_button").click(function() {
var id = $(this).attr('id');
$.ajax({
type: "POST",
url: "/accounts/" + my_app.username + "/listview/",
data: { entryname:id },
success: function(response){
alert(response.success);
}
});
return false;
});
});
</script>
将csrf令牌添加到您的ajax请求中
csrfmiddlewaretoken: '{{ csrf_token }}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.