飲歌長(zhǎng)嘯
2023-02-07 13:54:18
我的 Django Rest Framework 項(xiàng)目有模型字段,任何經(jīng)過(guò)身份驗(yàn)證的用戶都可以在其中創(chuàng)建模型實(shí)例。但是我想確保只有 Django Admin 可以更改accepted字段值。防止其他用戶更改accepted字段的最佳方法是什么?請(qǐng)注意,我想為經(jīng)過(guò)身份驗(yàn)證的用戶保留創(chuàng)建保留默認(rèn)accepted 字段的模型實(shí)例的權(quán)限。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貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
更改了視圖層和序列化程序
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')
添加回答
舉報(bào)
0/150
提交
取消