Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 不能同时设置“只读”和“只写”`_Django_Django Rest Framework - Fatal编程技术网

Django 不能同时设置“只读”和“只写”`

Django 不能同时设置“只读”和“只写”`,django,django-rest-framework,Django,Django Rest Framework,在我的项目中,我想将密码设置为只读(因为我有一个单独的端点来重置密码)和只写(因为我不想在响应中发送密码) 这是我的序列化程序: class UserSerializer(serializers.ModelSerializer): """A Serizlier class for User """ class Meta: model = models.User fields = ('id', 'email', 'phone_number', 'u

在我的项目中,我想将密码设置为
只读
(因为我有一个单独的端点来重置密码)和
只写
(因为我不想在响应中发送密码)

这是我的序列化程序:

class UserSerializer(serializers.ModelSerializer):
    """A Serizlier class for User """

    class Meta:
        model = models.User
        fields = ('id', 'email', 'phone_number', 'user_type', 'password')
        extra_kwargs = { 'password': { 'write_only': True} }
        read_only_fields = ('password',)
但我得到一个错误,说:

AssertionError at/api/user/21/

不能同时设置
只读
只写


如何使字段既为
只读
又为
只写

覆盖序列化程序的
\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo()
方法

class UserSerializer(serializers.ModelSerializer):
    """A Serizlier class for User """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.context['some_flag']:
            self.fields['password'].read_only = True
        else:
            self.fields['password'].write_only = True

    class Meta:
        model = models.User
        fields = ('id', 'email', 'phone_number', 'user_type', 'password')
        # extra_kwargs = { 'password': { 'write_only': True} } # remove this
        # read_only_fields = ('password',) # remove this
class UserSerializer(serializers.ModelSerializer):
“”“用户的Serizlier类”“”
定义初始化(self,*args,**kwargs):
super()
if self.context['some_flag']:
self.fields['password'].read_only=True
其他:
self.fields['password'].write_only=True
类元:
model=models.User
字段=(‘id’、‘电子邮件’、‘电话号码’、‘用户类型’、‘密码’)
#extra_kwargs={'password':{'write_only':True}}}删除此项
#只读字段=('password',)#删除此项

some_flag
变量应该从密码重置视图或从另一个视图传递给序列化程序。通常,如果有两个端点使用类似的序列化程序,而该序列化程序只需要与某个字段/功能不同,那么您将创建一个基类并对其进行抽象并且只更改/修改需要更改的部分。这就是我要做的

class (serializers.ModelSerializer):
    """A Serizlier class for User """

    class Meta:
        model = models.User
        fields = ('id', 'email', 'phone_number', 'user_type', 'password')
        extra_kwargs = { 'password': { 'read_only': True} }


class UserSerializerForOtherView(UserSerializer):

    class Meta(UserSerializer.Meta):
        extra_kwargs = { 'password': { 'write_only': True} }
现在,
UserSerializerForOtherView
继承了与
UserSerializer
相同的行为,如果您想进一步扩展此序列化程序的功能,您现在还拥有了一个新的序列化程序


您所需要做的就是告诉另一个视图使用另一个序列化程序。

因此扩展@JPG的答案

序列化程序

class ProfileSerializer(serializers.ModelSerializer):
    name = serializers.CharField()

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    if 'create_method' in self.context:
        self.fields['name'].write_only = True
    else:
        self.fields['name'].read_only = True
和视图集

class ProfileViewSet(viewsets.ModelViewSet):
    serializer_class = ProfileSerializer

def get_serializer_context(self):

    # Call Parent
    context = super().get_serializer_context()

    # Check If This Is a POST
    if self.request.method == 'POST':
        context['create_method'] = True

    # Handoff
    return context

这将允许在帖子上写下姓名,并在其他内容上只读

很抱歉,我不知道如何使用
某些标志
?你能举例说明吗?你能把这两种观点加起来吗?太好了!非常感谢。