Django rest framework DRF登录api返回的电子邮件已存在
这是我的型号(CustomUser): 我有以下序列化程序:Django rest framework DRF登录api返回的电子邮件已存在,django-rest-framework,django-allauth,Django Rest Framework,Django Allauth,这是我的型号(CustomUser): 我有以下序列化程序: class UserLoginSerializer(serializers.ModelSerializer): token = serializers.CharField(allow_blank=True, read_only=True) class Meta: model = CustomUser fields = ('email', 'password', 'token',) extra_kw
class UserLoginSerializer(serializers.ModelSerializer):
token = serializers.CharField(allow_blank=True, read_only=True)
class Meta:
model = CustomUser
fields = ('email', 'password', 'token',)
extra_kwargs = {
'password': {'write_only': True}
}
def validate(self, data):
print('$$$$$$$$$$$$$$$$$$$$$$$$$ validate $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
print('data:')
print(data)
user_obj = None
### E-mail validation
email = data.get("email", None)
if not email:
raise ValidationError(_('email must be filled out.'))
try:
user_obj = get_object_or_404(CustomUser, pk=email)
except CustomUser.DoesNotExist:
raise serializers.ValidationError("E-mail does not exist")
if user_obj and user_obj.status != 'A':
raise serializers.ValidationError("E-mail does not exist")
if not user_obj.exists():
raise ValidationError(_('User does not exist.'))
### Password validation
password = data.get("password", None)
if not password:
raise ValidationError(_('Password must be filled out.'))
if user_obj:
if not user_obj.check_password(password):
raise ValidationError(_('Incorrect credentials. Please try again.'))
elif user_obj.is_active:
data['user'] = user_obj
return data
#################################################################################
这是一种观点:
class UserLoginAPIView(APIView):
def post(self, request, *args, **kwargs):
data = request.data
serializer = UserLoginSerializer(data=request.data)
if serializer.is_valid():
user = serializer.validated_data['user']
django_login(request, user)
token, created = Token.objects.get_or_create(user=user)
return Response({"token": token.key}, status=status.HTTP_200_OK)
else:
print('%%%%%%%%%%%%%%%%%%%%%%%%%%% serializer errors %%%%%%%%%%%%%%%%%%%%%%%%')
print(serializer.errors)
return Response(data, status=status.HTTP_400_BAD_REQUEST)
当我执行到api的POST时,会出现以下错误:
%%%%%%%%%%%%%%%%%%%%%%%%%%%序列化程序错误%
{'email':[ErrorDetail(string='user with this-mail已经存在',code='unique')]}
错误请求:/users/api/login/
Allauth似乎截获了该请求,并将其验证为注册请求,而不是登录
我尝试过使用rest auth库,得到了相同的结果
我想有什么建议可以替代Allauth吗
谢谢
这是我的users/url.py文件:
from django.urls import path, include
from . import views
urlpatterns = [
path("api/register/", registration_view, name="register"),
path("api/login/", views.UserLoginAPIView.as_view(), name="login"),
path("rest-auth/", include('rest_auth.urls')),
]
我正在使用rest\u框架authtoken中的令牌:
from django.contrib.auth import get_user_model, login as django_login, logout as django_lougout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse, reverse_lazy
from django.views.generic.edit import CreateView
from django.views.generic import DetailView, RedirectView, UpdateView
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.authtoken.models import Token
import allauth
哦!!我理解这个问题。您使用的是根据模型序列化数据的。正因为如此,序列化程序正在检查电子邮件是否唯一(如您在模型中定义的) 我们可以对您的代码做一些改进,但为了使其正常工作并达到
validate
功能,您应该更改序列化程序
从rest\u框架导入序列化程序
类UserLoginSerializer(serializers.Serializer):
email=serializers.EmailField(必需=False,允许为空=True)
password=serializers.CharField(style={'input\u type':'password'})
token=serializers.CharField(allow\u blank=True,read\u only=True)
一旦进入validate
功能,您可能不会得到任何用户,因为您正在查找pk=email
,但您没有在您的模型中将email
定义为pk
。请尝试以下方法:
get_object_或_404(CustomUser,email=email)
更改此选项
fields = ('email', 'password', 'token',)
到
这应该是可行的。根据您的错误消息,我可以说您的UserLoginAPIView正在处理该请求。你能添加你的URL文件吗?此外,令牌模型是由您自己创建的,或者它来自哪里?@mathias.lantan我刚刚添加了URL文件。该令牌来自rest\u框架authtoken。谢谢谢谢你@Mathias!这就解决了这个错误。但是,在代码失败后,由于:“您配置了多个身份验证后端,因此必须提供
backend
参数或设置用户的backend
属性。”因此,我必须在“get_object_或_404(CustomUser,email=email)”之后添加以下内容user_obj.backend='django.contrib.auth.backends.ModelBackend'
fields = ('email', 'password', 'token',)
fields = ('username', 'password', 'token',)