allow post requests in django REST framework

独自空忆成欢 提交于 2021-02-09 11:12:38

问题


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

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?


回答1:


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


来源:https://stackoverflow.com/questions/50443849/allow-post-requests-in-django-rest-framework

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