jquery - Django Tastypie 总是返回 401 未经授权

标签 jquery python ajax django tastypie

我对我的 tastypie 资源使用 ajax 请求,但即使我使用 SessionAuthentication() 和 DjangoAuthorization(),它也总是 401。

资源.py

class EventsResource(ModelResource):

user = fields.ForeignKey(UserResource, 'user')

    class Meta:
        queryset = Event.objects.all()
        resource_name = 'events'
        filtering = {'start': ALL,
                     'end':ALL
                     }
        list_allowed_methods = ['get', 'post','put', 'patch']
        detail_allowed_methods = ['get', 'post', 'put', 'delete']
        authentication = SessionAuthentication()
        authorization = Authorization()
        include_resource_uri = True
        limit = 0
        always_return_data = True

这是一个日历资源,所以我有一个事件模型,我的ajax请求位于django-admin中加载的javascript文件中;我还检查了请求 header 是否具有 csrf token 和 session id,但它不起作用。

.ajax({
                    url:  event.resource_uri,
                    dataType: 'json',
                    contentType: 'application/json; encode=UTF-8',
                    type: 'DELETE',
                    success: function () {
                        $calendar.fullCalendar('removeEvents');
                        $calendar.fullCalendar('refetchEvents');
                        $('#modal-confirm').modal('hide');
                        showmsg('Evento eliminato correttamente', 'warning');
                    }
                });

最佳答案

您正在使用SessionAuthentication,但尚未提供 CSRF token header (我看到您检查了它,但它没有出现在您的代码中)。

在包含 JavaScript 的页面中的某处包含 {% csrf_token %} 标记,然后修改 AJAX 方法以使用 X-CSRF-Token header 设置 beforeSend选项:

$.ajax({
    url:  event.resource_uri,
    dataType: 'json',
    contentType: 'application/json; encode=UTF-8',
    type: 'DELETE',
    beforeSend: function(jqXHR) {
        jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val());
    },
    success: function () {
        $calendar.fullCalendar('removeEvents');
        $calendar.fullCalendar('refetchEvents');
        $('#modal-confirm').modal('hide');
        showmsg('Evento eliminato correttamente', 'warning');
    }
});

关于jquery - Django Tastypie 总是返回 401 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23674337/

相关文章:

javascript - 所见即所得的 niceEdit 编辑器不适用于通过 ajax-php 调用生成的文本区域

javascript - 非常简单的 toggleClass 不起作用

jQuery - 修改提示/警报功能

HTML 中的 Python 脚本

python - 使用正则表达式查找Python中两个定义标签之间多行字符串的所有出现

javascript - 为什么 $($) 会使我的页面崩溃?

python - 在 PyQt5 中显示和隐藏多个窗口

Javascript - 页面刷新后循环继续运行

javascript - 发布附加了 jQuery 的动态输入

jquery - 将 fancybox 与来自 AJAX 调用的内容结合使用