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

标签 python django django-rest-framework graphene-python

我正在使用带有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/

相关文章:

python - 将股票代码与其 EPS 评级合并

python - 如何在 Django 模型选择中使用 unicode 字符?

python - Django事件流过滤目标模型中外键的​​操作

django - 在 Django 中创建模板时迭代模型属性

python - django-hstore 与 Django 1.6 的兼容性问题

Django 2.2+调用rest api,过滤id列表

python - Django Rest Framework - 在列表中获取完整的相关对象

python - Pyparsing 标识符被压入堆栈两次

python - django 休息框架 : <object> is not JSON serializable

python - 如何使用 Selenium 和 Python 从通过 xpath 找到的 webdriver 元素中提取文本