CSRF Protection Deep Dive
CSRF (Cross-Site Request Forgery) attacks trick users into submitting forms on your site from another site. Django's CSRF middleware adds a secret token to every form that must be present on POST requests. Understanding CSRF is critical for web security.
15 min•By Priygop Team•Updated 2026
How CSRF Protection Works
- Django generates a unique CSRF token per session
- {% csrf_token %} adds a hidden input with the token
- On POST, middleware validates the token matches
- If token is missing/invalid, Django returns 403 Forbidden
- CsrfViewMiddleware handles this automatically
- AJAX requests include token in X-CSRFToken header
- @csrf_exempt — Disable CSRF for specific views (use carefully!)
- CSRF protects against forged form submissions from malicious sites
CSRF in Practice
CSRF in Practice
# Template — always include {% csrf_token %}
# <form method="post">
# {% csrf_token %}
# {{ form.as_p }}
# <button type="submit">Submit</button>
# </form>
# AJAX/JavaScript — include CSRF token in header
# function getCookie(name) {
# const value = document.cookie
# .split('; ')
# .find(row => row.startsWith(name + '='));
# return value ? value.split('=')[1] : null;
# }
#
# fetch('/api/posts/', {
# method: 'POST',
# headers: {
# 'Content-Type': 'application/json',
# 'X-CSRFToken': getCookie('csrftoken'),
# },
# body: JSON.stringify({ title: 'New Post' }),
# });
# Exempting views (rare — only for external webhooks/APIs)
# from django.views.decorators.csrf import csrf_exempt
# @csrf_exempt
# def webhook(request):
# # Handle external webhook
# passTip
Tip
Use pagination with paginate_by in ListView. Django handles page navigation and boundary checks automatically.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not handling empty querysets. Add get_queryset() checks or use the empty template pattern for better UX.
Practice Task
Note
(1) Add paginate_by=10 to ListView. (2) Add pagination navigation to template. (3) Test with lots of data.
Quick Quiz
Key Takeaways
- CSRF (Cross-Site Request Forgery) attacks trick users into submitting forms on your site from another site.
- Django generates a unique CSRF token per session
- {% csrf_token %} adds a hidden input with the token
- On POST, middleware validates the token matches