将序列化程序错误作为响应以列表格式传递

时间:2019-07-26 01:04:09

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

我正在将graphene_djangorest_framework serializers一起使用。当我遇到验证问题时,出现如下错误

"{'email': [ErrorDetail(string='user with this Email Address already exists.', code='unique')]}",

如何以列表方式传递错误,就像密码不匹配时传递的错误?

这是我现在正在做的事情

class Register(graphene.Mutation):
    class Arguments:
        email = graphene.String(required=True)
        password = graphene.String(required=True)
        password_repeat = graphene.String(required=True)

    user = graphene.Field(UserQuery)
    token = graphene.String()
    success = graphene.Boolean()
    errors = graphene.List(graphene.String)

    @staticmethod
    def mutate(self, info, email, password, password_repeat):
        if password == password_repeat:
            try:
                serializer = RegistrationSerializer(data={'email': email, 'password': password, 'is_confirmed': False})
                print('#########Serializer########', serializer)
                if serializer.is_valid(raise_exception=True):
                    print('serializer is valid')
                    user = serializer.save()
                    auth = authenticate(username=email, password=password)
                    login(info.context, auth)
                    return Register(success=True, user=user, token=get_token(auth))
                print('############serializer errors##########', serializer.errors)
                return Register(success=False, token=None, errors=['email/password', 'Unable to login'])
            except ValidationError as e:
                print("validation error", e)
                return Register(success=False, errors=[e])
        return Register(success=False, errors=['password', 'password is not matching'])

0 个答案:

没有答案