Django休息框架在部署后为post方法返回405

时间:2015-04-16 18:09:47

标签: python django django-rest-framework

我正在使用Django rest框架开发API。在我当地,一切都很好。我也使用招摇来记录我的API,我可以看到我的帖子并获得方法。

问题是,当我将代码部署到服务器时,我得到了405个代码用于我的post方法,并且无法在swagger上看到post方法。他们只是消失了。

这是我的api:

Views.py:

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from api.models import Clinic
from api.serializers import ClinicSerializer
from rest_framework.views import APIView
from django.http import Http404
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view



class ClinicList(APIView):
    """
    List all clinics
    """
    def get(self, request, format = None):
        clinics = Clinic.objects.all()
        serializer = ClinicSerializer(clinics, many = True)
        return Response(serializer.data)
    """
    Save new clinic
    """
    def post(self, request, format = None):
        serializer = ClinicSerializer(data=request.data)
        if(serializer.is_valid()):
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

解决方案urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('api.urls')),
    url(r'^docs/', include('rest_framework_swagger.urls')),
]

api.urls:

    urlpatterns = [
    url(r'^Clinic/$', views.ClinicList.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

为什么我的帖子方法得到405?

2 个答案:

答案 0 :(得分:0)

重新启动服务器时问题已解决。代码似乎没有错。

答案 1 :(得分:0)

您可以尝试: 仅将您的ClinicList导入为:

urlpatterns = [
    path("clinic", ClinicList.as_view()),
]