无法使用提供的凭据登录

时间:2020-07-23 09:26:50

标签: python django django-rest-framework

当我尝试登录时,在注册新帐户(使用令牌)方面没有任何问题,我收到此错误。 无法使用提供的凭据登录。,在此先感谢您帮助我解决此问题。我在代码中错过了什么吗?

这是我的serializers.py

class RegistrationSerializer(serializers.ModelSerializer):

    password2               = serializers.CharField(style={'input_type': 'password'}, write_only=True)

    class Meta:
        model = Account
        fields = ['email', 'username', 'password', 'password2']
        extra_kwargs = {
                'password': {'write_only': True},
        }   


    def save(self):

        account = Account(
                    email=self.validated_data['email'],
                    username=self.validated_data['username']
                )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        account.set_password(password)
        account.save()
        return account

我的views.py

@api_view(['POST', ])
def registration_view(request):

    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = 'successfully registered new user.'
            data['email'] = account.email
            data['username'] = account.username
            token = Token.objects.get(user=account).key
            data['token'] = token
        else:
            data = serializer.errors
        return Response(data)

这是我的设置。py

INSTALLED_APPS = [
    
    .....
    'homepage',
]
AUTH_USER_MODEL = 'homepage.Account'
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

这是我的urls.py

from rest_framework.authtoken.views import obtain_auth_token

app_name='homepage'

urlpatterns = [
  path('api/login/', obtain_auth_token),
  path('api/registration_view/', views.registration_view),
]

1 个答案:

答案 0 :(得分:1)

首先,在您的设置中,您将默认身份验证设置为

rest_framework.authentication.TokenAuthentication

但是在您看来,您已经用[SessionAuthentication, BasicAuthentication]装饰了它,应该是TokenAuthentication 看来您正在使用drf令牌身份验证,在这种情况下,您完全不需要编写登录视图,只需这样做

from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
    path('yourloginurl', obtain_auth_token)
]

当您使用电子邮件代替用户名的自定义模型时,您的帖子请求应该为

{
    "username" : "usermail@mail.com",
    "password": "userpassword"
}
相关问题