一尘不染

Django Rest Framework:创建对象后禁用字段更新

django

试图通过Django Rest Framework API调用使我的用户模型成为RESTful,以便我可以创建用户并更新其个人资料。

但是,当我与用户一起执行特定的验证过程时,我不希望用户在创建帐户后能够更新用户名。我尝试使用read_only_fields,但这似乎在POST操作中禁用了该字段,因此在创建用户对象时无法指定用户名。

我该如何实施呢?目前存在的API的相关代码如下。

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'email')
        write_only_fields = ('password',)

    def restore_object(self, attrs, instance=None):
        user = super(UserSerializer, self).restore_object(attrs, instance)
        user.set_password(attrs['password'])
        return user


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    serializer_class = UserSerializer
    model = User

    def get_permissions(self):
        if self.request.method == 'DELETE':
            return [IsAdminUser()]
        elif self.request.method == 'POST':
            return [AllowAny()]
        else:
            return [IsStaffOrTargetUser()]

谢谢!


阅读 726

收藏
2020-03-30

共1个答案

一尘不染

似乎你需要用于POST和PUT方法的不同序列化器。在用于PUT的序列化器方法中,你仅可以除去用户名字段(或将用户名字段设置为只读)。

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    serializer_class = UserSerializer
    model = User

    def get_serializer_class(self):
        serializer_class = self.serializer_class

        if self.request.method == 'PUT':
            serializer_class = SerializerWithoutUsernameField

        return serializer_class

    def get_permissions(self):
        if self.request.method == 'DELETE':
            return [IsAdminUser()]
        elif self.request.method == 'POST':
            return [AllowAny()]
        else:
            return [IsStaffOrTargetUser()]
2020-03-30