mdadil2019
mdadil2019

Reputation: 819

allow post requests in django REST framework

I am creating a simple rest api using django REST framework. I have successfully got the response by sending GET request to the api but since I want to send POST request, the django rest framework doesn't allow POST request by default.

As in image(below) only GET,HEAD, OPTIONS are allowed but not the POST request enter image description here

The GET and POST methods inside of views.py

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from profiles_api import serializers
from rest_framework import status
# Create your views here.


class HelloApiView(APIView):
    """Test APIView"""

    #Here we are telling django that the serializer class for this apiViewClass is serializer.HelloSerializer class
    serializer_class = serializers.HelloSerializer

    def get(self, request, format=None):
    """Retruns a list of APIViews features."""

    an_apiview = [
        'Uses HTTP methods as fucntion (get, post, patch, put, delete)',
        'It is similar to a traditional Django view',
        'Gives you the most of the control over your logic',
        'Is mapped manually to URLs'
    ]

    #The response must be as dictionary which will be shown in json as response
    return Response({'message': 'Hello!', 'an_apiview': an_apiview})

    def post(self,request):
        """Create a hello message with our name"""

        serializer = serializer.HelloSerializer(data=request.data)

        if serializer.is_valid():
            name = serializer.data.get('name')
            message = 'Hello! {0}'.format(name)
            return Response({'message':message})
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

How to allow POST requests in django REST framework?

Upvotes: 5

Views: 9938

Answers (1)

JPG
JPG

Reputation: 88649

The problem with the code was, you have added the def post() after the return statement.

To solve, just correct your indentation level as below,

class HelloApiView(APIView):
    def get(self, request, format=None):
        return Response()

    def post(self, request):
        return Response()

Upvotes: 3

Related Questions