# 禁止访问（CSRF cookie 未设置）：/api/update/

- **ID:** `python/django-ajax-csrf-error`
- **领域:** python
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

AJAX 请求未在标头中包含 CSRF 令牌，或 cookie 缺失。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   Ensure CSRF cookie is set by using {% csrf_token %} in template, then include token in AJAX: headers: {'X-CSRFToken': getCookie('csrftoken')}
   ```
2. **** (90% 成功率)
   ```
   Use Django's ensure_csrf_cookie decorator on the view that returns the page.
   ```

## 无效尝试

- **** — Adding @csrf_exempt to view bypasses security, not recommended. (80% 失败率)
- **** — Hardcoding CSRF token in JavaScript doesn't work as it changes per session. (70% 失败率)
