AuthTokenSerializer.无效数据.期待字典,但得到请求.姜戈



对不起我的英语。我正在学习 django 休息,我想创建令牌授权。我通过教程做到了,但是将数据发送到服务器时出现错误

{
"non_field_errors": [
"Invalid data. Expected a dictionary, but got Request."
]
}

我的设置文件:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'users',
]
..
..
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'PAGE_SIZE': 10,
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}

我的网址

urlpatterns = [
url(r'^authtoken', views.ObtainAuthToken.as_view()),
]

我的观点

class ObtainAuthToken(APIView):
permission_classes = (permissions.AllowAny,)
serializer_class = AuthTokenSerializer
def post(self, request):
serializer = self.serializer_class(data=request)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status.HTTP_201_CREATED)

我不明白为什么我有错误

你需要将request.data传递到序列化程序中,而不仅仅是request

serializer = self.serializer_class(data=request.data)

最新更新