django rest框架post方法给出错误“方法”POST“不允许”

时间:2015-07-02 08:00:04

标签: python django django-rest-framework

我在运行api时收到错误'方法'POST“不允许”。我是DRF的新手,不知道我做错了什么。 GET方法工作正常。我有POST方法的问题。

我的代码在下面给出

view.py:

 from django.contrib.auth.models import User
 from django.http import Http404
 from django.shortcuts import get_object_or_404
 from restapp.serializers import UserSerializer
 from rest_framework.views import APIView
 from rest_framework.response import Response
 from rest_framework import status
 from django.http import HttpResponse

 class UserList(APIView):
  def get(self, request, format=None):
    users = User.objects.all()
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data)

 def post(self, request, format=None):
    serializer = UserSerializer(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)

serializer.py:

 from django.contrib.auth.models import User
 from .models import Question,Choice
 from rest_framework import serializers

 class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ('id', 'username', 'first_name', 'last_name', 'email')

url.py

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

 from restapp import views

 admin.autodiscover()


 urlpatterns = patterns('',
     url(r'^admin/', include(admin.site.urls)),
     url(r'^users/', views.UserList.as_view()),)

1 个答案:

答案 0 :(得分:3)

您的代码中有错误的标识。 post方法需要在UserList(APIView)类中。现在被定义为一个独立的功能。