Django rest框架验证POST请求参数的最佳方法

时间:2019-02-25 13:18:03

标签: python django django-rest-framework django-views

当我在Django rest框架POST类上收到APIView请求时,我想过滤/验证传递的参数以防止被修改。例如,对于此Serilizer:

class MediaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Media
        fields = ('id', 'title', 'content', 'url', 'createdByUser', 'karma', 'type', 'issue', 'creationDate', 'updatedDate')

不应修改诸如idcreationDatecreatedByUser之类的某些参数。因此,对于我的课程class MediaDetail(APIView),我有:


def validateRequest(self):
        user = self.request.data.get('createdByUser', None)
        karma = self.request.data.get('karma', None)
        creationDate = self.request.data.get('creationDate', None)

        if user is not None or karma is not None or creationDate is not None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
@method_decorator(login_required)
def post(self, request, pk, format=None):
        self.validateRequest()
        media = self.get_object(pk)
        self._throwIfNotMediaAuthor(media, request.user)

        serializer = MediaSerializer(media, data=request.data)

        if serializer.is_valid():
            # serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

是否有更好的方法进行验证?也许在序列化器上?我找不到足够的文档

1 个答案:

答案 0 :(得分:0)

是的,您可以在序列化程序的Meta上使用read_only_fields参数。

有关如何在当前视图内使用的示例(假设您想按REST's guidelines进行POST的创建对象时对其进行了一些修改):

class MediaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Media
        read_only_fields = ('id', 'karma', 'createdByUser', 'creationDate')
        ...

@method_decorator(login_required)
def post(self, request, pk, format=None):
        serializer = MediaSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(createdByUser=request.user, creationDate=timezone.now().date(), karma=initial_value)
        return Response(serializer.data, status=status.HTTP_201_CREATED)