๐Ÿ“ Django

CSRF Protection in Django

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
294
๐ŸŒฟ
Level
Medium

CSRF (Cross-Site Request Forgery) is an attack in which an adversary tricks the user’s browser into sending a request on the user’s behalf.

How Django CSRF Works

  1. Django creates a CSRF token when a template renders {% csrf_token %} or a view explicitly requests one
  2. Every HTML form with POST must include a hidden field containing the token
  3. Django compares the token from the form with the token in the cookie
  4. If they do not match โ€” the response is 403 Forbidden

Template Tag

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Submit</button>
</form>

{% csrf_token %} generates:

<input type="hidden" name="csrfmiddlewaretoken" value="abc123...">

AJAX Requests

// Get the token from the cookie
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}

fetch('/api/tasks/', {
    method: 'POST',
    headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({title: 'New Task'}),
});

Exempting an API Endpoint

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def api_endpoint(request):
    ...  # Validate an appropriate non-cookie credential here

Do not add csrf_exempt merely to silence a 403 response. It is appropriate only when the endpoint does not rely on cookie-based authentication and another secure authentication mechanism is enforced. DRF’s SessionAuthentication requires CSRF protection for unsafe methods; token-based authentication does not rely on CSRF tokens.

Middleware

MIDDLEWARE = [
    ...,
    'django.middleware.csrf.CsrfViewMiddleware',
    ...,
]

The middleware is included by default โ€” do not remove it.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 314
๐Ÿ“

Django Migrations

A migration is a file describing changes to the database schema. Django tracks the state...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 284
๐Ÿ“

Django Development Server

Django's built-in server is intended for local development: it runs the project and reloads Python...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 288
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum