【发布时间】:2019-06-03 10:29:49
【问题描述】:
我正在尝试在 API 中获取经过身份验证的用户。这是代码:-
DRF 视图
from braces.views import CsrfExemptMixin
from rest_framework import generics
class API(CsrfExemptMixin, generics.CreateAPIView):
authentication_classes = []
serializer_class = SomeSerializer
def post(self, request):
print(request.user.id) # None
Django 视图
from django.views import View
from braces.views import CsrfExemptMixin
class API(CsrfExemptMixin, View):
authentication_classes = []
def post(self, request):
print(request.user.id) # prints id of the user.
为什么我在 2 种不同的情况下得到不同的响应?以下是我的设置。
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
# Needed to login by email
'modules.profile.backend.EmailBackend'
)
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'EXCEPTION_HANDLER': 'modules.utils.exception_handler.custom_exception_handler',
'PAGE_SIZE': 10,
}
【问题讨论】:
-
您可以添加
CsrfExemptMixin引用吗? -
完成。请检查。
-
您的 Django 会话是如何配置的?您如何对此进行测试,即用于进行这些调用的前端是什么?应该没有区别。
-
我的前端是一个 Chrome 扩展程序,它在我的 POST 端点上触发跨域请求。
-
@PythonEnthusiast
print(request.user)的输出是什么?
标签: django django-rest-framework