在我的项目中,我想将密码设置为let x = -5;
let y = -5;
for (; x < 5; ++x) {
for (; y < 5; ++y) {
console.log(x);
}
}
(因为我有一个单独的端点来重置密码)和read_only
(因为我不希望在响应中发送密码)。 / p>
这是我的序列化器:
write_only
但是我收到一条错误消息:
/ p / user / 21 / 中的AssertionError
不能同时设置
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',)
和read_only
如何让一个字段同时为write_only
和read_only
?
答案 0 :(得分:2)
将序列化程序的 __init__()
方法替换为
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
some_flag
变量是您应该从密码重置视图或其他视图传递给序列化器的东西
答案 1 :(得分:1)
因此扩展了@JPG的答案
序列化器
log_prob
视图集
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
这将允许名称写在POST上,并且只能在其他所有内容上读取
答案 2 :(得分:0)
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
相同的行为,现在,如果您想进一步扩展此串行器的功能,则现在有了一个新的串行器。
您需要做的就是告诉另一个视图使用另一个序列化器。