Django Rest Framework,在POST上返回405

时间:2016-01-22 22:24:56

标签: python angularjs django python-3.x django-rest-framework

从DRF v3.0升级到v3.3.2后,尝试使用POST方法创建模型时,我得到405(方法不允许)。

我无法捕获调试器上的请求以找出它出错的地方。

我在Project / settings.py中的DRF设置:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGINATE_BY'             : 10
}

我的urlpatterns项目/ urls.py

urlpatterns = [
    ...
    url(r'^api/v1/seeds/', include('seed.urls')),
    ...
    url('^.*$', IndexView.as_view(), name='index')
]

我在项目/ seed / urls.py中的urlpatterns:

from django.conf.urls import url, include
from rest_framework import routers
from seed.views import SeedViewSet

router = routers.SimpleRouter()
router.register(r'^', SeedViewSet)

urlpatterns = [
    url(r'^', include(router.urls))
]

我的项目/ seed / views.py

from seed.serializers import SeedSerializer
from seed.models import Seed
from rest_framework import viewsets

class SeedViewSet(viewsets.ModelViewSet):
    queryset = Seed.objects.all()
    serializer_class = SeedSerializer
    # permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
        return super(SeedViewSet, self).perform_create(serializer)

我的项目/ seed / serializer.py

from authentication.serializers import AccountSerializer
from rest_framework import serializers
from seed.models import Seed


class SeedSerializer(serializers.ModelSerializer):
    user = AccountSerializer(read_only=True, required=False)

    class Meta:
        model = Seed
        fields = ('id', 'user', 'jobs', 'list_name', 'proxyType', 'created_at', 'updated_at')
        read_only_fields = ('id', 'user', 'jobs', 'created_at', 'updated_at')

我能做错什么? 或者是因为升级而我应该做些什么?

修改 我正在使用angularJs发布到API,这是我服务中的功能:

function create(list_name, proxyType) {
    return $http.post('/api/v1/seeds/', {
    list_name: list_name,
    proxyType: proxyType
    });
}

2 个答案:

答案 0 :(得分:0)

from rest_framework.decorators import list_route

请使用以下内容。

@list_route(methods=['post'])
def perform_create(self, request):
        serializer.save(user=self.request.user)
        return super(SeedViewSet, self).perform_create(serializer)

答案 1 :(得分:0)

我将SeedViewSet从viewsets.ModelViewSet更改为generics.ListCreateAPIView,然后我覆盖了post(self, request, *args, **kwargs)方法并且它有效。