我有一個API端點,當我嘗試進行獲取或部分更新時出現問題。我不確定我錯過了什麼,我已經將代碼包含在嘗試和錯誤中。Django Rest Framework返回「detail」:「未找到。」
錯誤:
"detail": "Not found."
據我明白的URL應該包括例如我想部分更新的ID,因此該URL來執行PATCH上是:
我的觀點:
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" } ]
這可能是因爲用戶沒有權限'PostOwnManuscriptLibrary' –
我需要延長我的權限的方法更新所有者或補丁? – NewScientists
當你只是確實得到與PK的URL是沒事的,你看到的對象序列化? –