Interview question
What is Django's CSRF protection and how does it work with views? Django का CSRF protection क्या है और views के साथ कैसे काम करता है?
Answer
Django's CsrfViewMiddleware protects against Cross-Site Request Forgery by requiring a secret token to be present and valid on state-changing requests (POST, PUT, DELETE), rejecting requests that don't include it.
# In a template - the {% csrf_token %} tag inserts a hidden input
# book_form.html
<form method='post'>
{% csrf_token %}
<input type='text' name='title'>
<button type='submit'>Save</button>
</form>
# Without {% csrf_token %}, submitting this form returns:
# 403 Forbidden - CSRF verification failed
# For AJAX/JavaScript requests, the token must be sent as a header
# JS example
# function getCookie(name) { ... } // extract csrftoken cookie
# fetch('/api/books/', {
# method: 'POST',
# headers: { 'X-CSRFToken': getCookie('csrftoken') },
# body: JSON.stringify({title: 'New Book'})
# });
# Exempting a specific view from CSRF checks (use carefully!)
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def webhook_receiver(request):
# only exempt views that use a DIFFERENT authentication mechanism
# (e.g. signature verification for webhooks), never for regular forms
pass
# Class-based view CSRF exemption
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class WebhookView(View):
def post(self, request):
pass
# Django REST Framework handles CSRF differently - session-authenticated
# requests still need it, but token/API-key authenticated requests are exempt
# by DRF's authentication classes automatically
# Common cause of CSRF errors in development: forgetting {% csrf_token %}
# in a form, or making an AJAX POST without including the token headerDjango का CsrfViewMiddleware Cross-Site Request Forgery से बचाता है, state-changing requests (POST, PUT, DELETE) पर एक secret token चाहिए, बिना token वाली requests reject होती हैं।
# Template में - {% csrf_token %} tag hidden input insert करता है
# book_form.html
<form method='post'>
{% csrf_token %}
<input type='text' name='title'>
<button type='submit'>Save</button>
</form>
# बिना {% csrf_token %} submit करने पर:
# 403 Forbidden - CSRF verification failed
# AJAX/JS requests के लिए token header में भेजना ज़रूरी है
# fetch('/api/books/', {
# method: 'POST',
# headers: { 'X-CSRFToken': getCookie('csrftoken') },
# body: JSON.stringify({title: 'New Book'})
# });
# किसी specific view को CSRF checks से exempt करना (सावधानी से!)
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def webhook_receiver(request):
pass
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class WebhookView(View):
def post(self, request):
passWas this answer clear?