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

Django应用集成Reportlab时出现CSRF token缺失/错误403问题

Django AJAX请求CSRF报错修复方案

1. 模板添加CSRF令牌

在你的custom_bingo.html的<body>标签内任意位置添加Django模板标签:

{% csrf_token %}

该标签会自动渲染为隐藏的input元素,存储当前用户的CSRF校验令牌。

2. AJAX请求头携带令牌

修改你的JS脚本,发送请求前读取令牌并加入请求头,以下为原生JS和jQuery两种实现参考:

原生JS写法

// 读取CSRF令牌
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// 读取表格数据转为数组的逻辑你可以按自己的需求实现,这里假设已经生成了tableData数组
const tableData = [];

fetch('/get_custom_bingo', {
  method: 'POST',
  headers: {
    'X-CSRFToken': csrftoken,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(tableData)
})
.then(response => response.blob())
.then(blob => {
  // 触发PDF下载
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'custom_bingo.pdf';
  a.click();
  window.URL.revokeObjectURL(url);
})

jQuery写法

const csrftoken = $('input[name="csrfmiddlewaretoken"]').val();
const tableData = []; // 你自己的表格数据数组

$.ajax({
  url: '/get_custom_bingo',
  type: 'POST',
  headers: {'X-CSRFToken': csrftoken},
  data: JSON.stringify(tableData),
  contentType: 'application/json',
  xhrFields: {
    responseType: 'blob'
  },
  success: function(blob) {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'custom_bingo.pdf';
    a.click();
    window.URL.revokeObjectURL(url);
  }
})

3. 后端视图参考配置

不需要添加csrf_exempt装饰器(存在安全风险),正常处理数据生成PDF返回即可,views.py参考代码:

import io
import json
from django.http import HttpResponse
from reportlab.pdfgen import canvas

def get_custom_bingo(request):
    if request.method == 'POST':
        # 读取前端传入的数组
        data_list = json.loads(request.body)
        # 这里写你自己的数组处理逻辑
        
        # 调用Reportlab生成PDF
        buffer = io.BytesIO()
        p = canvas.Canvas(buffer)
        # 这里写你自己的PDF绘制逻辑
        p.showPage()
        p.save()
        buffer.seek(0)
        
        # 返回PDF响应
        response = HttpResponse(buffer, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="custom_bingo.pdf"'
        return response

异常排查

如果修改后仍然报错,在settings.py中添加CSRF信任域名配置,本地测试参考配置如下:

CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:8000', 'http://localhost:8000']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:09:03