【发布时间】:2017-08-30 05:30:17
【问题描述】:
我尝试创建一个视图,它将接受 POST 请求并创建我的模型的新实例(见帖子底部)。我遵循this 教程。问题是,当我访问与视图关联的 URL 时,它继承自 CreateAPIView,我没有看到用于创建新实例的 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
我的 urls.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
【问题讨论】:
-
您想知道为什么
CreateApiView不接受GET吗?你会期待什么回应?如果要在同一条路由上使用多个方法,可以使用 ModelViewSets。 -
我想实现和底部截图一样的效果
-
好的。我误解了。你的问题现在很有意义。回复看起来不像我期望的
CreateAPIView。它看起来像ListAPIView -
可能是由于您的权限设置。在我的 django 设置中
REST_FRAMEWORK = {...'DEFAULT_PERMISSION_CLASSES: ['rest_framework.permissions.AllowAny']'}这当然是最佳实践,并且应该始终进行某种身份验证。
标签: django django-rest-framework