如何返回与用户端点一起验证的电子邮件?

我已经实现了 DRF 并且不想强制电子邮件验证,但仍然使用它(在屏幕上提醒他们)。我只想返回 account_emailaddress.verified 和用户端点。实现这一目标的最佳方法是什么?我尝试从这篇文章中获取提示,但没有成功。


account_emailaddress 来自我实现的 django-allauth 应用程序 https://github.com/pennersr/django-allauth/blob/master/allauth/account/models.py


序列化器:


class UserSerializer(serializers.ModelSerializer):

class Meta:

    model = models.CustomUser

    fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', 'avatar')

看法:


class UserView(generics.RetrieveUpdateDestroyAPIView):

queryset = CustomUser.objects.all()

serializer_class = UserSerializer


def get(self, request, *args, **kwargs):

    try:

        user = self.queryset.get(pk=kwargs["user"])

        return Response(UserSerializer(user).data)

    except CustomUser.DoesNotExist:

        return Response(

            data={

                "message": "User with id: {} does not exist".format(kwargs["user"])

            },

            status=status.HTTP_404_NOT_FOUND

        )


def put(self, request, *args, **kwargs):

    try:

        user = self.queryset.get(pk=kwargs["user"])

        serializer = UserSerializer()

        user = serializer.update(user, request.data)

        return Response(UserSerializer(user).data)

    except CustomUser.DoesNotExist:

        return Response(

            data={

                "message": "User with id: {} does not exist".format(kwargs["user"])

            },

            status=status.HTTP_404_NOT_FOUND

        )

编辑:感谢 schillingt 的回答,我能够根据需要修改序列化程序


from allauth.account.models import EmailAddress    


class UserSerializer(serializers.ModelSerializer):

verified_email = serializers.SerializerMethodField()

class Meta:

    model = models.CustomUser

    fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', 'avatar', 'verified_email')


def get_verified_email(self, obj):

    try:

        email_address = EmailAddress.objects.get(user_id=obj.id)

        return email_address.verified

    except EmailAddress.DoesNotExist:

        return None


RISEBY
浏览 181回答 2
2回答

qq_花开花谢_0

如果我只想要不同序列化程序上的字段,我过去所做的方法是使用SerializerMethod该类。我猜在课堂上account_emailaddress。class UserSerializer(serializers.ModelSerializer):    verified_email = serializers.SerializerMethod()    class Meta:        model = models.CustomUser        fields = (..., 'verified_email')    def _verified_email(self, obj):        try:            return obj.account_emailaddress.verified        except EmailAddress.DoesNotExist:            return None然后在视图集,你应该包括account_emailaddress在select_related对queryset属性,使之不会使每一个额外的查询CustomUser。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python