【问题标题】:UpdateAPIView not working: Method "PATCH" not allowedUpdateAPIView 不起作用:不允许使用方法“PATCH”
【发布时间】:2017-10-01 12:34:47
【问题描述】:

我使用 Django 和 Django REST Framework 来实现 RESTful API

我现在拥有的:

  • ContentEntry 模型
  • 我的ContentEntry 模型的ContentEntryCreateUpdateSerializer 序列化程序
  • ContentEntryCreate 视图可创建一些 ContentEntryies
  • ContentEntryUpdate 视图更新 ContentEntryies

代码如下:

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 属性中看到的,服务器似乎只允许使用POSTOPTIONS 方法。

这很奇怪,因为generics.UpdateAPIView 定义了putpatch 方法。

我不认为这是一个权限问题,因为我允许一切:

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ]
}

我应该怎么做允许 HTTP PATCHPUT 方法

【问题讨论】:

    标签: python django rest django-rest-framework


    【解决方案1】:

    请确保用开始和结束(^ 和 $ 符号)标记 URL。

    这里发生的情况是没有结束标记,r'content-entry' 匹配“/content-entry/4/”,因此调用创建视图。

    请改用:r'^content-entry$'r'^content-entry/(?P&lt;id&gt;\d+)$'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-29
      • 2018-11-12
      • 2018-10-02
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2021-08-27
      相关资源
      最近更新 更多