我的 Django Rest Framework 项目有模型字段,任何经过身份验证的用户都可以在其中创建模型实例。但是我想确保只有 Django Admin 可以更改accepted字段值。防止其他用户更改accepted字段的最佳方法是什么?请注意,我想为经过身份验证的用户保留创建保留默认accepted 字段的模型实例的权限。MODELS.PYclass PO(models.Model): name = models.CharField(max_length=100) accepted=models.BooleanField(default=False) # I want this field to be changed only by admin userVIEWS.PYclass POcreate(generics.CreateAPIView): queryset = PO.objects.all() serializer_class = POserializer permission_classes = [permissions.IsAuthenticated]SERIALIZER.PYclass POserializer(serializers.ModelSerializer): class Meta: model=PO fields='__all__'
1 回答
慕斯王
TA贡献1864条经验 获得超2个赞
更改了视图层和序列化程序
def get_serializer_class(self):
if self.request.user.is_staff:
return POAdminserializer
return POserializer
class POAdminserializer(serializers.ModelSerializer):
class Meta:
model=PO
fields='__all__'
class POserializer(serializers.ModelSerializer):
class Meta:
model=PO
exclude=('created','accepted','delivered','rejected','rejected_reason')
添加回答
举报
0/150
提交
取消