我正在尝试在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,
}
答案 0 :(得分:2)
您尚未定义要使用DRF的任何身份验证后端。您应该在视图中指定它:
from rest_framework.authentication import SessionAuthentication
class API(CsrfExemptMixin, generics.CreateAPIView):
authentication_classes = [SessionAuthentication]
或从视图中完全删除authentication_classes
并在您的REST_FRAMEWORK设置中添加SessionAuthentication后端:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
...
}