django rest framework post method giving error “Method ”POST“ not allowed”

时间秒杀一切 提交于 2021-01-28 14:38:41

问题


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.

my code is given below

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:


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.



来源:https://stackoverflow.com/questions/31178759/django-rest-framework-post-method-giving-error-method-post-not-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!