python - 无法使用提供的凭据登录
问题描述
当我尝试登录时,我在注册新帐户(带有令牌)时没有任何问题我收到此错误。无法使用提供的凭据登录。,在此先感谢曾经帮助我解决这个问题的人。我错过了我的代码中的某些内容吗?
这是我的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),
]
解决方案
首先,在您的设置中,您已将默认身份验证设置为
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"
}
推荐阅读
- python-3.x - 如何使用 scp 命令将多个文件从 unix 复制到窗口?
- java - 外部 ProgressBar 未与按钮操作侦听器同时运行
- google-apps-script - 当用户选择范围内的单元格时,Google App Script 执行函数
- powershell - Select-Object 确实转换数据,但也将语句保留在它的数据中
- angular - agm-snazzy-info-window 显示在随机位置
- python - 来自 lxml 的意外 htmlelement 结果
- python - tkinter 绑定到“
"不工作 - node.js - 使用 Node FileSystem fs.writeFileSync() 将 JSON 数据写入文件
- azure - ADF 映射数据流 - 重用单个运行的 spark 集群以并行执行映射数据流
- html - 在模态对话框中实现下拉菜单:我无法设置动态显示的值