Django Rest Framework - CreateAPIView 不允许使用 POST 方法

标签 django django-rest-framework

我尝试创建一个 View ,它将接受 POST 请求并创建我的模型的新实例(见帖子底部)。我关注 this教程。问题是,当我访问从 CreateAPIView 继承的与 View 关联的 URL 时,我没有看到用于创建新实例的 API 的 html 表示形式,而且我还看到它接受 GET 请求,而不是文档中提到的 POST。

页面看起来像这样

enter image description here

我的意见.py

from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView
from datingapp.models import Profile
from .serializers import ProfileSerializer, ProfileCreateSerializer

class ProfilesAPIView(ListAPIView):
  queryset = Profile.objects.all()
  serializer_class = ProfileSerializer

class ProfileCreateAPIView(CreateAPIView):
  queryset = Profile.objects.all()
  serializer_class = ProfileCreateSerializer

我的网址.py
from django.conf.urls import url
from django.contrib import admin

from datingapp.views import ProfilesAPIView, ProfileCreateAPIView

urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'api/profiles/', ProfilesAPIView.as_view(), name='list'),
   url(r'api/profiles/create/$', ProfileCreateAPIView.as_view(), name='create')
   ]

我的序列化程序.py
from rest_framework.serializers import ModelSerializer
from datingapp.models import Profile

class ProfileSerializer(ModelSerializer):
  class Meta:
    model = Profile
    fields = [
        'name',
        'age',
        'heigth'
        'location',
    ]

class ProfileCreateSerializer(ModelSerializer):
  class Meta:
    model = Profile
    fields = [
        'name',
        'age',
        'heigth'
        'location',
    ]  

在我的settings.py 中,我安装了crispy_forms。

我究竟做错了什么 ?

UPD:这就是我想要实现的目标

enter image description here

如您所见,有一个表单,它仅接受 POST 并表示不允许 GET

最佳答案

问题出在您的路由器上。第一个模式匹配 api/profiles/api/profiles/create/所以第二个永远不会被评估。您看到的是 ProfilesAPIView 而不是创建 View 。

 url(r'api/profiles/', ProfilesAPIView.as_view(), name='list'),
 url(r'api/profiles/create/$', ProfileCreateAPIView.as_view(), name='create')

要修复它,请交换 url 的顺序,或添加 $到第一个模式的结尾。 r'api/profiles/$'

关于Django Rest Framework - CreateAPIView 不允许使用 POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37619589/

相关文章:

javascript - Csrf 验证失败 - Django Rest 和 Backbone.js

python - 帮助浏览/跟踪(大型)python 项目源代码的工具

python - requests.post() 的 CSRF 验证失败

django - unQL 和 Django?

python - 字段名称 user_username 对于模型配置文件无效

python - 当表单验证错误发生时,我如何指定它们?

python - DjangoRestFramework - 加载特定列并保存整个对象

Django-REST框架restore_object attrs参数

docker - 如何在 Docker 中为多个微服务创建集中式身份验证服务器

python - 如何使用 AJAX 或类似的东西在 Django 中使用 Python 脚本?