首页 > 解决方案 > 无法使用提供的凭据登录

问题描述

当我尝试登录时,我在注册新帐户(带有令牌)时没有任何问题我收到此错误。无法使用提供的凭据登录。,在此先感谢曾经帮助我解决这个问题的人。我错过了我的代码中的某些内容吗?

这是我的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

我的意见.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)

这是我的 settings.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),
]

标签: pythondjangodjango-rest-framework

解决方案


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

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"
}

推荐阅读