Skip to main content
 首页 » 编程设计

python之Django Rest Framework 如何禁止用户更改用户名

2025年05月04日29softidea

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

感谢您的任何建议。

PS:我用的是python3.6和django2.1

编辑:我正在使用 generics.{ListCreateAPIView|RetrieveUpdateDestroyAPIView} View 类。像这样:

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 

EDIT2:有一个重复的问题(可能是我的问题)here

请您参考如下方法:

假设您正在为 View 使用 viewset 类,那么您可以覆盖 init 方法序列化器为,

class UserSerializer(serializers.ModelSerializer): 
    <b>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)</b> 
 
    class Meta: 
        ....

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

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

来自doc

Note: By default include_docs_urls configures the underlying SchemaView to generate public schemas. This means that views will not be instantiated with a request instance. i.e. Inside the view self.request will be None.


在答案中,字段在请求对象的帮助下弹出动态。
因此,如果您还希望处理 API 文档,请定义多个 序列化程序并有效地使用get_serializer_class() 方法。这就是 DRF 方式。