2017-09-05 160 views
3

我有一個API端點,當我嘗試進行獲取或部分更新時出現問題。我不確定我錯過了什麼,我已經將代碼包含在嘗試和錯誤中。Django Rest Framework返回「detail」:「未找到。」

錯誤:

"detail": "Not found."

據我明白的URL應該包括例如我想部分更新的ID,因此該URL來執行PATCH上是:

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, "manuscript": 9, "bookmarks": "test success", "history": "test success" } ]

+1

這可能是因爲用戶沒有權限'PostOwnManuscriptLibrary' –

+0

我需要延長我的權限的方法更新所有者或補丁? – NewScientists

+1

當你只是確實得到與PK的URL是沒事的,你看到的對象序列化? –

回答

2

補丁,讓你需要從id使用值的細節,你的情況,這是28,試着去路徑和補丁

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

哇,這是一個忽視一個地獄。再次感謝@bearbrown – NewScientists

+0

只是最後一個問題。此路徑假定我知道庫的ID。我的ManuscriptItem模型中如何進入ManuscriptLibrary並獲取ManuscriptLibrary實例的ID,它們只與外鍵相關? – NewScientists

相關問題