我使用 Django 和 Django REST Framework 来实现 RESTful API。
我现在拥有的:
ContentEntry
模型- 用于我的
ContentEntry
模型的ContentEntryCreateUpdateSerializer
序列化程序 ContentEntryCreate
View ,用于创建一些ContentEntry
iesContentEntryUpdate
View 以更新ContentEntry
ies
代码如下:
from django.db import models
from rest_framework import serializers
from rest_framework import generics
from rest_framework.views import APIView
from my_api_app import views
# models.py
class ContentEntry(models.Model):
content = models.ForeignKey(Content)
quantity = models.IntegerField()
container = models.ForeignKey(Container, related_name='content_entries')
# serializers.py
class ContentEntryCreateUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = ContentEntry
fields = ('id', 'content', 'quantity', 'container')
# views.py
class ContentEntryCreate(generics.CreateAPIView):
queryset = ContentEntry.objects.all()
serializer_class = ContentEntryCreateUpdateSerializer
# views.py
class ContentEntryUpdate(generics.UpdateAPIView):
queryset = ContentEntry.objects.all()
lookup_field = 'id'
serializer_class = ContentEntryCreateUpdateSerializer
# urls.py
urlpatterns = [
url(r'content-entry', views.ContentEntryCreate.as_view()),
url(r'content-entry/(?P<id>\d+)$', views.ContentEntryUpdate.as_view()),
]
除了总是返回错误的 ContentEntryUpdate
之外,一切正常:
HTTP/1.1 405 Method Not Allowed
Allow: POST, OPTIONS
Content-Type: application/json
Date: Wed, 03 May 2017 14:40:03 GMT
Server: WSGIServer/0.2 CPython/3.6.1
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
{"detail":"Method \"PATCH\" not allowed."}
正如您在Allow
属性中看到的,服务器似乎只允许POST
和OPTIONS
方法。
这很奇怪,因为 generics.UpdateAPIView
定义了 put
和 patch
方法。
我不认为这是一个权限问题,因为我允许一切:
# settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
]
}
我应该怎么做才能允许 HTTP PATCH
和 PUT
方法?
最佳答案
请确保用开始和结束(^ 和 $ 符号)标记 URL。
这里发生的是没有结束标记,r'content-entry'
匹配“/content-entry/4/”,因此调用创建 View 。
使用:r'^content-entry$'
和 r'^content-entry/(?P<id>\d+)$'
相反。
关于python - UpdateAPIView 不工作 : Method "PATCH" not allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43764094/