user2649907
user2649907

Reputation: 25

django rest framework post method giving error "Method "POST" not allowed"

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()),)

Upvotes: 1

Views: 4919

Answers (1)

argaen
argaen

Reputation: 4255

You have improper indentation in your code. The post method needs to be inside the UserList(APIView) class. Right now is defined as a standalone function.

Upvotes: 4

Related Questions