gpt4 book ai didi

Django Rest 框架电子邮件验证

转载 作者:行者123 更新时间:2023-12-02 03:51:15 25 4
gpt4 key购买 nike

我想在注册前验证电子邮件 ID 是否已存在于用户模型中

这是我的带有验证的序列化器

class RegistrationSerializer(serializers.Serializer):
username = serializers.CharField(max_length=100)
email = serializers.EmailField()
password = serializers.CharField(max_length=100)

def validate_email(self,attrs):
email=attrs['email']
print email
if email:
emailset = Q(email__icontains=email)
emailres = User.objects.filter(emailset)
if emailres:
msg = _('The email address is already taken')
raise serializers.ValidationError(msg)
else:
return attars

它抛出错误“TypeError:字符串索引必须是整数”

 email=attrs['email']

类型错误:字符串索引必须是整数

最佳答案

我猜您已经升级或使用 DRF 3.x,因此不再有 attrs 字典,而是值。请参阅field-level-validation

那边已经有一个 UniqueValidator 。所以我认为你可以这样做:

class RegistrationSerializer(serializers.Serializer):
#...
email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())])

关于Django Rest 框架电子邮件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29813463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com