“方法\”POST \“不允许。” Django REST

时间:2017-12-16 14:23:09

标签: django-rest-framework django-rest-auth

我是django休息框架的新手。我有一个api来为每个用户获取相应的令牌。定义为访问令牌的方法是

class ObtainAuthToken(APIView):

def post(self, request):
    user = authenticate(
        username=request.data['username'], password=request.data['password'])
    if user:
        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key, 'user': UserSerializer(user).data})
    return Response('Invalid username or password', status=status.HTTP_400_BAD_REQUEST)

在urls.py中我有

url(r'^login/$',ObtainAuthToken, name='login')

但是在登录用户时,我收到的回复是

{
"detail": "Method \"POST\" not allowed."
}

我哪里出错?

2 个答案:

答案 0 :(得分:1)

首先 - 我看到您使用了django-rest-auth标记。你真的在使用rest auth吗?如果没有 - 你应该考虑这样做,因为它提供了大量的auth功能。

关于您的问题,您忘记在您的网址中致电as_view() ObtainAuthToken。像这样改变并告诉我它是否有效:

url(r'^login/$', ObtainAuthToken.as_view(), name='login')

答案 1 :(得分:0)

您的代码中有错误的标识。 post方法需要在ObtainAuthToken(APIView)类中。现在被定义为一个独立的功能。

相关问题