CSRF Protection (Django)

Django protects against Cross-Site Request Forgery by requiring a secret token on every POST form. You add {% csrf_token %} inside the form, and CsrfViewMiddleware rejects POST requests that lack a valid token.

Django

CSRF attacks trick a logged-in user's browser into submitting a forged request. Django blocks this by issuing a per-session token: forms must include it, and the middleware verifies it on every unsafe request (POST, PUT, DELETE), returning 403 if it is missing or wrong.

In templates the protection is one line: put {% csrf_token %} just inside your <form>. Django's CsrfViewMiddleware (enabled by default) handles the verification. For AJAX requests you send the token in the X-CSRFToken header, reading it from the csrftoken cookie.

Never disable CSRF protection on a real form view. For APIs that use token authentication instead of cookies, Django REST Framework handles CSRF appropriately, and the @csrf_exempt decorator exists only for narrow, well-understood cases like webhooks.

Syntax

<form method="post">{% csrf_token %} ... </form>

Examples

Python

<!-- template -->
<form method="post">
  {% csrf_token %}
  <input name="title">
  <button>Save</button>
</form>

<!-- AJAX: send token in the X-CSRFToken header -->

Learn it in a lesson

See also

Back to the Dictionary