Django Rest Framework:AssertionError

时间:2016-03-05 19:53:35

标签: python django permissions django-rest-framework

我有Django Rest Framework的问题,我正在学习将 权限和关联 设置为我的API,因此我无法运行服务器所以它说 AssertionError:Field(read_only = True)应为ReadOnlyField

我的model.py

class Task(models.Model):
    owner=models.ForeignKey('auth.User',related_name='tasks')
    completed=models.BooleanField(default=False)
    title=models.CharField(max_length=100)
    description=models.TextField()

serializer.py

class TaskSerializer(serializers.ModelSerializer):
    owner=serializers.Field('owner.username')
    class Meta:
        model = Task
        fields=('title','description','completed','owner ')

permission.py

class IsOwnerOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method is SAFE_METHODS:
            return True

        return obj.owner==request.user

views.py

class TasksMixins(object):
    queryset = Task.objects.all()
    serializer_class=TaskSerializer
    permission_classes=(IsOwnerOrReadOnly,)

    def pre_save(self,obj):
        obj.owner=self.request.user

class TaskList(ListCreateAPIView):
    pass

class TaskDetail(RetrieveUpdateDestroyAPIView):
    pass

我不确定我搞砸了什么。非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

问题可能在于owner.username,因为我看不到您如何直接更新此问题。

尝试

class TaskSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        read_only=('owner.username',)
        fields=('title','description','completed','owner.username')

答案 1 :(得分:0)

IsOwnerOrReadOnly类正在尝试将属性所有者与记录的用户进行比较,但在您的序列化程序中,您只有用户名而不是用户本身,序列化程序应该是这样的:

class TaskSerializer(serializers.ModelSerializer):
    owner_username=serializers.Field('owner.username', read_only=True)
    class Meta:
    model = Task
    fields=('title','description','completed','owner', 'owner_username')

此外,您还需要验证对象是否具有所有者属性:

class IsUserOwner(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method is SAFE_METHODS:
            if not hasattr(obj, 'owner'):
                return True

            return obj.owner == request.user
        return True