我正在尝试在 Django 中编写一个非常基本的 AJAX 请求,并且在 Chrome Dev 和 Django 控制台中不断收到 403 禁止错误。我前几天发布了一个类似的问题,并尝试了所有建议的解决方案,包括 @csrf_exempt (以排除这是否是一个 csrf 问题),我尝试在 AJAX POST 请求中包含 csrfmiddlewaretoken: '{{ csrf_token }}' (在数据下方),这也没有解决问题。这是我的代码。
def profile_listview(request, username,
template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
user = get_object_or_404(get_user_model(),
username__iexact=username)
fullsalelist = Entry.objects.filter(author__username__iexact=username)
@csrf_exempt
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 },
});
return false;
});
});
</script>
网址
(r'^accounts/(?P<username>[\@\.\w-]+)/listview/$', profile_listview),
值得注意的事情:
我在设置中打开了 csrf 中间件
在 jQuery AJAX 代码中,url 和数据都发送了正确的信息
当我单击删除按钮时,出现 403 禁止错误。
打印“request is ajax”不会在控制台(或任何地方)中打印。
我也很困惑,因为我得到的信息相互矛盾。有人告诉我应该通过 javascript 添加 csrf 值( https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/ )。这给我留下了两个问题。 1. 这与在 POST 请求中添加 csrfmiddlewaretoken: '{{ csrf_token }}' 有什么不同? 2. 更重要的是,我在使用 @csrf_exempt 时仍然遇到 403 错误,这难道不是一个没有意义的问题吗?
最佳答案
@csrf_exempt 需要位于 urls.py 调用的函数之前。在OP的示例中,delete_object从未被调用,因为在调用没有装饰器的profile_listview时已经发生了错误。
顺便说一句,如果 URL 不存在,可能会遇到类似的情况(使用 @csrf_exempt 但收到 403)。由于某种原因(安全?),它将返回 403 而不是 404,因此很难调试。
关于jquery - 为什么在 AJAX 请求中使用 @csrf_exempt 时会收到 403 Forbidden 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990202/