我尝试创建一个 View ,它将接受 POST 请求并创建我的模型的新实例(见帖子底部)。我关注 this教程。问题是,当我访问从 CreateAPIView 继承的与 View 关联的 URL 时,我没有看到用于创建新实例的 API 的 html 表示形式,而且我还看到它接受 GET 请求,而不是文档中提到的 POST。
页面看起来像这样
我的意见.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:这就是我想要实现的目标
如您所见,有一个表单,它仅接受 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/