如何让用户只在django rest框架中修改他们的数据?

时间:2013-08-01 16:23:06

标签: django api django-rest-framework

我有一个只应由所有者修改的位置模型

class Location(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    address = models.TextField()

这是API位置序列化程序

class LocationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Location
        fields = ('user', 'name', 'address',)

问题是我希望用户成为请求用户

实际上我覆盖了viewset的create方法,但我认为这不是最好的解决方案

class LocationViewSet(mixins.CreateModelMixin,
                mixins.RetrieveModelMixin,
                mixins.ListModelMixin,
                GenericViewSet):
    model = Location
    serializer_class = LocationSerializer

    def get_queryset(self):
        return self.model.objects.filter(user=self.request.user)

    def create(self, request, *args, **kwargs):
        data = request.DATA.copy()
        data.update({'user':unicode(self.request.user.id)})

        serializer = self.get_serializer(data=data, files=request.FILES)

        if serializer.is_valid():
            self.pre_save(serializer.object)
            self.object = serializer.save(force_insert=True)
            self.post_save(self.object, created=True)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED,
                        headers=headers)

            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

感谢您的任何建议

1 个答案:

答案 0 :(得分:0)

您想要调整example from the tutorial about associating snippets with users。保留get_queryset实施,然后将user字段设置为pre_save中的请求用户。