Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 9 of 9 · Django Forms & Validation
Interview question

What is CSRF protection in the context of Django forms, and how does {% csrf_token %} relate to it? Django forms के context में CSRF protection क्या है, और {% csrf_token %} से इसका क्या रिश्ता है?

Answer

Every form that submits via POST needs {% csrf_token %} to include Django's CSRF protection token, proving the request originated from your own site and not a malicious third party.

<!-- Every POST form MUST include this -->
<form method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Submit</button>
</form>
<!-- Renders as: <input type='hidden' name='csrfmiddlewaretoken' value='...'> -->

<!-- GET forms do NOT need csrf_token - GET requests should be safe/idempotent
     and don't modify data, so CSRF protection doesn't apply to them -->
<form method='get'>
    <input type='text' name='q'>
    <button type='submit'>Search</button>
</form>

<!-- Common error without the token -->
<!-- Forbidden (403) CSRF verification failed. Request aborted. -->

# For AJAX form submissions, include the token in headers instead
# JavaScript
# const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
# fetch('/submit/', {
#     method: 'POST',
#     headers: { 'X-CSRFToken': csrftoken },
#     body: formData
# });

# The CSRF token is tied to the user's session - Django's
# CsrfViewMiddleware validates it automatically for all POST/PUT/
# PATCH/DELETE requests unless the view is explicitly @csrf_exempt

# Testing forms in Django's test client automatically handles CSRF
from django.test import Client
client = Client(enforce_csrf_checks=True)  # simulates real browser CSRF behavior
response = client.post('/books/create/', {'title': 'Test'})
# fails with 403 unless the test explicitly fetches and includes a valid token

POST से submit होने वाले हर form में {% csrf_token %} शामिल होना चाहिए, Django का CSRF protection token देता है, यह साबित करता है कि request आपकी site से ही आई है।

<!-- हर POST form में यह ज़रूरी है -->
<form method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Submit</button>
</form>

<!-- GET forms को csrf_token की ज़रूरत नहीं -->
<form method='get'>
    <input type='text' name='q'>
    <button type='submit'>Search</button>
</form>

<!-- बिना token के common error -->
<!-- Forbidden (403) CSRF verification failed. -->

# AJAX submissions के लिए token headers में
# const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
# fetch('/submit/', {
#     method: 'POST',
#     headers: { 'X-CSRFToken': csrftoken },
#     body: formData
# });

# CSRF token user की session से जुड़ा होता है

from django.test import Client
client = Client(enforce_csrf_checks=True)
response = client.post('/books/create/', {'title': 'Test'})

Was this answer clear?