You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署Django REST Framework API后POST请求报错的解决咨询

解决Django REST Framework POST请求的403与500错误

一、修复Postman返回的500服务器错误

终端报错明确指向:AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'>

问题原因

你的employeeList类中post方法存在两个致命问题:

  • 未接收request参数(APIView的视图方法必须接收request对象)
  • 未返回任何合法响应,仅用pass占位

修复代码

修改views.py中的post方法,实现完整的POST逻辑:

class employeeList(APIView):
    def get(self, request):
        employees1 = employees.objects.all()
        serializer = employeeSerializer(employees1, many=True)
        return Response(serializer.data)
    
    def post(self, request):  # 必须接收request参数
        serializer = employeeSerializer(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)

二、修复浏览器POST的403 CSRF错误

当DEBUG=False时,Django的CSRF中间件会严格校验请求中的CSRF token,但API接口通常不需要依赖Session的CSRF验证(一般用Token/JWT认证)。

解决方法(二选一)

方法1:直接关闭当前视图的CSRF验证

在views.py中导入装饰器,给类添加豁免:

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class employeeList(APIView):
    # 已实现的get、post方法...

方法2:使用DRF标准认证机制(推荐)

对于生产环境的API,更规范的做法是配置Token认证,同时关闭CSRF依赖:

  1. 在settings.py中添加DRF配置:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}
  1. 在views.py中配置认证类:
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

class employeeList(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]  # 如需登录才能访问API
    
    # 已实现的get、post方法...

额外规范建议

  • 模型类名遵循Python大驼峰命名规范,建议将employees改为Employee
  • 确保employeeSerializer正确定义,包含模型所有字段:
from rest_framework import serializers
from .models import employees

class employeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = employees
        fields = '__all__'

内容的提问来源于stack exchange,提问作者Mhmdnzr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:45:32