python
auth_error
ai_generated
true
禁止访问(CSRF cookie 未设置):/api/update/
Forbidden (CSRF cookie not set.): /api/update/
ID: python/django-ajax-csrf-error
80%修复率
88%置信度
0证据数
2026-02-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
AJAX 请求未在标头中包含 CSRF 令牌,或 cookie 缺失。
English
AJAX request does not include CSRF token in headers or cookie is missing.
解决方案
-
95% 成功率
Ensure CSRF cookie is set by using {% csrf_token %} in template, then include token in AJAX: headers: {'X-CSRFToken': getCookie('csrftoken')} -
90% 成功率
Use Django's ensure_csrf_cookie decorator on the view that returns the page.
无效尝试
常见但无效的做法:
-
80% 失败
Adding @csrf_exempt to view bypasses security, not recommended.
-
70% 失败
Hardcoding CSRF token in JavaScript doesn't work as it changes per session.