📝 Django

CSRF Protection in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
72
🌿
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. On the first visit, Django sets a csrftoken cookie
  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):
    ...  # Only when using a different authentication method (tokens)

DRF automatically exempts CSRF for API requests authenticated with 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

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 132
📝

AI Agents: ReAct Loop and Autonomous Actions

A chatbot answers questions. An agent takes action: it calls tools, retrieves real data, and...

📅 30.06.2026 👁️ 100
📝

RAG: Chatting with Documents via Vector Search

RAG (Retrieval-Augmented Generation) is a pattern for working with your own documents. Instead of fine-tuning...

📅 30.06.2026 👁️ 92

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!