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

Django跳转404问题求助:无法正确传入verification_code参数

问题分析与解决

问题根源

你遇到的404错误核心原因是:Django模板标签是在后端渲染完成的,前端JavaScript无法动态修改其生成的URL内容。当前代码里的{% url 'pdfcertificate:pdf_certificate' pk='data.verification_code' %}会直接把字符串data.verification_code拼进请求URL,导致地址变成pdf-certificate/data.verification_code/,而非实际的验证码值。

修复方案

有两种实用的解决方式:

方式1:直接拼接URL路径

利用已知的URL前缀和JS变量直接拼接跳转地址:

// 替换原跳转代码
window.location.href = `/pdf-certificate/${data.verification_code}/`;

方式2:占位符替换(适配URL规则变更)

先在模板中生成带占位符的基础URL,再用JS替换为实际验证码:

<!-- 在<script>块外先定义模板URL -->
<script>
const certificateUrlTemplate = "{% url 'pdfcertificate:pdf_certificate' pk='__CODE__' %}";
</script>

<!-- 在fetch回调中替换占位符并跳转 -->
.then(() => {
    console.log("verification code", data.verification_code);
    const actualUrl = certificateUrlTemplate.replace('__CODE__', data.verification_code);
    window.location.href = actualUrl;
});

验证注意事项

  • 确认data.verification_code为有效字符串/数字(Django的<str:pk>规则兼容数字类型)
  • 检查URLconf中pdf-certificate/<str:pk>/的路径前缀与拼接内容一致

内容的提问来源于stack exchange,提问作者Amina K M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:12:34