gpt4 book ai didi

python - 不调用序列化程序创建函数

转载 作者:行者123 更新时间:2023-12-04 00:03:20 25 4
gpt4 key购买 nike

我正在使用带有graphql的rest框架序列化程序。我试图在用户注册时创建一个用户,并根据用户在创建帐户时选择的角色创建一个配置文件。为此,我添加了一个序列化器层,但是当我使用 serializer.save 时不会调用序列化器创建函数在我的 mutate 函数中。为什么呢?

这是我的做法

class Register(graphene.Mutation):
"""
Mutation to register a user
"""
class Arguments:
email = graphene.String(required=True)
password = graphene.String(required=True)
password_repeat = graphene.String(required=True)
role = graphene.String(required=True)

success = graphene.Boolean()
errors = graphene.List(graphene.String)
email = graphene.String()

def mutate(self, info, email, password, password_repeat, role):
if password == password_repeat:
try:
serializer = RegistrationSerializer(data={
'email': email,
'password': password,
'is_active': False,
'role': role,
})
if serializer.is_valid():
print("valid")
user = serializer.save()
# user.set_password(password)
print ("user is ###########", user)
# user = UserModel.objects.create(
# email=email,
# role=role,
# is_active=False
# )
# user.set_password(password)
# user.save()
print ("seraizlier after saving", serializer.validated_data.get('id'))
if djoser_settings.get('SEND_ACTIVATION_EMAIL'):
send_activation_email(user, info.context)
return Register(success=bool(user.id), email=user.email)
else:
print("serializer error", serializer.errors)
# TODO: specify exception
except Exception as e:
print("exception", e)
errors = ["email", "Email already registered."]
return Register(success=False, errors=errors)
errors = ["password", "Passwords don't match."]
return Register(success=False, errors=errors)


class RegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'role', 'is_active', 'password', )

def create(self, validated_data):
print ("validated_data", validated_data) # not logged in the terminal
user = User.objects.create(
email=validated_data['email'],
role=validated_data['role'],
is_active=validated_data['is_active']
)
user.set_password(validated_data['password'])
user.save()
print (" role ", validated_data['role'])
if (validated_data['role'] == "end_user" or validated_data['role'] == "agent"):
Profile.objects.create(user=user)
else:
Company.objects.create(user=user)
return user

最佳答案

你有一个缩进错字。 create应该是RegistrationSerializer的方法,但正如所写,它是 Meta 的一种方法类(class)。

修复缩进,你应该很高兴:

class RegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'role', 'is_active', 'password', )

def create(self, validated_data):
...

关于python - 不调用序列化程序创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55284663/

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