gpt4 book ai didi

django - 允许在 Django REST 框架中发布请求

转载 作者:行者123 更新时间:2023-12-04 01:56:11 24 4
gpt4 key购买 nike

我正在使用 django REST 框架创建一个简单的 rest api。我已通过向 api 发送 GET 请求成功获得响应,但由于我想发送 POST 请求,默认情况下 django rest 框架不允许 POST 请求。

如下图所示,仅允许 GET、HEAD、OPTIONS,但不允许 POST 请求 enter image description here

views.py 中的 GET 和 POST 方法

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?

最佳答案

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

要解决,只需更正您的 indentation 级别,

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

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

关于django - 允许在 Django REST 框架中发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50443849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com