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

Django API接口403错误求助:CSRF cookie未设置问题排查

排查Django APIView 403 CSRF错误问题

问题分析

你遇到的403错误提示“CSRF cookie未设置”,尽管给视图添加了csrf_exempt装饰器但未生效,同时代码存在缩进错误会导致后续逻辑无法正常执行。

解决方案

1. 修正csrf_exempt装饰器的应用方式

类级别的@method_decorator有时会因装饰器顺序、继承关系等原因失效,改用直接装饰dispatch方法的方式更可靠:

from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView

class ApproveOrDeclineUserView(APIView):
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)
    
    def patch(self, request, org_code, user_id):
        # 原patch方法内的逻辑(需修正缩进)
        try:
            organization = Organization.objects.get(code=org_code)
        except Organization.DoesNotExist:
            return Response({'detail': 'Invalid organization code'}, status=status.HTTP_404_NOT_FOUND)

        try:
            user = ClientUser.objects.get(id=user_id, organization=organization)
        except ClientUser.DoesNotExist:
            return Response({'detail': 'User not found in this organization'}, status=status.HTTP_404_NOT_FOUND)

        # 后续决策判断及邮件发送逻辑...

2. 修正代码缩进错误

你提供的代码中,第二个try块与patch方法同级,这会导致user变量无法在后续的决策判断逻辑中访问,引发NameError。必须将该try块缩进至patch方法内部,与第一个try块保持同级。

3. 额外检查项

  • 确认前端发送的请求方法为PATCH,视图仅处理PATCH请求,方法不匹配也可能引发异常。
  • 检查项目中是否存在自定义CSRF相关中间件或装饰器,是否对该视图路径额外施加了CSRF保护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:57:26