在Django控制台中,我收到红色的消息:
[16/Jan/2015 01:33:34] "POST /accounts/benjamin/listview HTTP/1.1" 404 7562
在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
这是我的查看方法:(请注意,我刚刚阅读了其他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/')
模板中的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>
答案 0 :(得分:1)
将csrf标记添加到您的ajax请求
csrfmiddlewaretoken: '{{ csrf_token }}'