我对我的 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/