我已经实现了 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
qq_花开花谢_0
相关分类