2017-08-15 161 views
0

对不起,我的英语。我学习Django的休息,我想创建令牌授权。我做到了通过教程,但我有错误,当数据发送到服务器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) 

我不明白为什么我有呃ror

+1

能向我们展示完整的追溯?在哪里发生错误? – devxplorer

+0

@devxplorer谢谢你的回答。我没有错误,当我尝试登录一些用户我有答案:'“无效的数据。期望一个字典,但得到请求。”'我发送请求像[this](http://take.ms/AfgHB)不能理解为什么。可以我做错了 –

回答

1

您需要将request.data(而不仅仅是request)传递到串行器。

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

wooww,谢谢!愚蠢,愚蠢的错误((( –

相关问题