本文介绍了Django Rest Framework如何禁止用户更改其用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建 UserSerializer ,并希望允许用户创建新帐户,但禁止他们更改用户名.我可以应用一个 read_only 属性,但是在创建新用户名时,用户将无法设置用户名.但是没有它,它允许我更改它.还有一个 required 属性,不幸的是它不能与read_only一起使用.没有其他相关属性.一种解决方案是创建两个不同的序列化器,一个用于创建用户,另一个用于更改用户,但这似乎是一件丑陋且错误的事情.您对不编写2个序列化器如何实现这一点有什么建议吗?

I'm creating UserSerializer and want to allow users to create new accounts but forbid them to change their usernames. There is a read_only attribute that I can apply but then users won't be able to set a username when creating a new one. But without that It allows me to change it. There is also a required attribute which unfortunately cannot be used with read_only. There is no other relevant attribute.One solution is to create 2 different Serializers one for creating User and another from changing him, but that seems the ugly and wrong thing to do. Do you have any suggestions on how to accomplish that without writing 2 serializers?

谢谢您的建议.

PS:我正在使用python3.6和django2.1

PS: I'm using python3.6 and django2.1

我使用的是泛型.{ListCreateAPIView | RetrieveUpdateDestroyAPIView} 类用于视图.像这样:

I'm using generics.{ListCreateAPIView|RetrieveUpdateDestroyAPIView} classes for views. Like this:

class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserDetails(generics.RetrieveUpdateAPIView):
    # this magic means (read only request OR accessing user is the same user being edited OR user is admin)
    permission_classes = (perm_or(ReadOnly, perm_or(IsUserOwner, IsAdmin)),)

    queryset = User.objects.all()
    serializer_class = UserSerializer

存在一个重复的问题(可能是我的重复)

There is a duplicate question (probably mine is duplicate) here

推荐答案

假设您在视图中使用 viewset 类,则可以覆盖序列化器的 init 方法为

Assuming you are using a viewset class for your view, then you could override the init method of serializer as,

class UserSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if 'view' in self.context and self.context['view'].action in ['update', 'partial_update']:
            self.fields.pop('username', None)

    class Meta:
        ....

如果您尝试在更新( HTTP PUT )或部分更新( HTTP PATCH )时更新用户名字段,则序列化程序将删除 用户名" 字段,因此不会影响数据/模型

更新
为什么上面的答案不能用 documentaion API 唤醒?

文档

If you are trying to update the username field while update (HTTP PUT) or partial update (HTTP PATCH), the serializer will remove the username field from the list of fields and hence it wont affect the data/model

UPDATE
Why the above answer not woking with documentaion API?

From the doc


在答案中,借助于 request 对象,这些字段是 弹出 动态.
因此,如果您还希望处理API文档,请定义 multiple 序列化器,并有效地使用 get_serializer_class() 方法.这就是DRF方式.


In the answer, the fields are pops out dynamically with the help of a request object.
So, If you wish to handle API documentaion also, define multiple serializer and use get_serializer_class() method efficently. That's the DRF way.

这篇关于Django Rest Framework如何禁止用户更改其用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:27