django rest框架发布方法给出错误“方法"POST"不允许" [英] django rest framework post method giving error "Method "POST" not allowed"
本文介绍了django rest框架发布方法给出错误“方法"POST"不允许"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
运行api时出现错误不允许使用方法"POST"".我是DRF的新手,也不知道我做错了什么.GET方法工作正常.我对POST方法有疑问.
I am getting error 'Method "POST" not allowed' while running the api. I am new to DRF and don’t know what i am doing wrong. the GET method is working fine. I have problem with POST method.
我的代码如下
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:
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()),)
推荐答案
您的代码中的标识错误.post方法必须位于UserList(APIView)类内部.现在已定义为独立功能.
You have wrong identation in your code. The post method needs to be inside the UserList(APIView) class. Right now is defined as a standalone function.
这篇关于django rest框架发布方法给出错误“方法"POST"不允许"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文