允许在Django REST框架中发布请求 [英] allow post requests in django REST framework

查看:57
本文介绍了允许在Django REST框架中发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django REST框架创建一个简单的rest api.我已经通过将GET请求发送到api成功地获得了响应,但是由于我想发送POST请求,因此django rest框架默认情况下不允许POST请求.

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.

与图像(如下图)一样,仅允许GET,HEAD,OPTIONS,但不允许POST请求

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

views.py内的GET和POST方法

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)

如何在django REST框架中允许POST请求?

How to allow POST requests in django REST framework?

推荐答案

该代码的问题是,您在 return 语句后添加了 def post().

要解决此问题,只需按如下所示纠正您的 Indentation 级别,

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

这篇关于允许在Django REST框架中发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆