Django Rest Framework返回“详细信息”:“未找到”。

时间:2017-09-05 14:38:07

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

当我尝试进行获取或部分更新时,我有一个API端点有问题。我不确定我缺少什么,我已经包含了尝试的代码和它给出的错误。

错误:

  

“detail”:“找不到。”

据我所知,url应该包含我想要部分更新的实例的ID,所以执行PATCH的url是:

  

http://localhost:8000/manuscripts-api/manuscriptlibrary/9/

我的观点:

class ManuscriptLibraryViewSet(viewsets.ModelViewSet):
    """Handles creating, reading and updating manuscript library."""

    authentication_classes = (TokenAuthentication,)
    serializer_class = serializers.ManuscriptLibrarySerializer
    queryset = models.ManuscriptLibrary.objects.all()
    permission_classes = (permissions.PostOwnManuscriptLibrary,)

    def put(self, request, *args, **kwargs):
        return self.partial_update(request, *args, **kwargs)

我的模特:

class ManuscriptLibrary(models.Model):
    """Represents a single manuscript's library"""

    manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE)
    bookmarks = models.CharField(max_length=99999999)
    history = models.CharField(max_length=99999999)

    def __str__(self):
        """Django uses when it needs to convert the object to a string"""
        return str(self.manuscript)

我的序列化器:

class ManuscriptLibrarySerializer(serializers.ModelSerializer):
    """A serializer for a manuscript's library."""

    class Meta:
        model = models.ManuscriptLibrary
        fields = ('id', 'manuscript', 'bookmarks', 'history')

我的网址:

router = DefaultRouter()
router.register('manuscripts', views.ManuscriptViewSet, base_name="manuscripts")  # auto basename for models
router.register('manuscriptlibrary', views.ManuscriptLibraryViewSet, base_name="manuscript_library")
router.register('manuscriptsettings', views.ManuscriptSettingsViewSet)

urlpatterns = [
    url(r'', include(router.urls))
]

我的许可:

class PostOwnManuscriptLibrary(permissions.BasePermission):
    """Allow author to update a manuscript's library they own."""

    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.manuscript.author == request.user

    def has_permission(self, request, view):
        if request.method == 'POST':
            manuscript = request.data.get('manuscript')
            instance = ManuscriptItem.objects.get(pk=manuscript)
            return instance.author == request.user
        return True

其他信息:

地址:

http://localhost:8000/manuscripts-api/manuscriptlibrary/

返回:

  

[       {           “id”:28,           “手稿”:9,           “书签”:“测试成功”,           “历史”:“测试成功”       }]

1 个答案:

答案 0 :(得分:2)

要获取补丁并获取详细信息,您需要使用id中的值,在您的情况下,这是28,请尝试转到路径,然后修补

http://localhost:8000/manuscripts-api/manuscriptlibrary/28/