Django — CSRF
What is CSRF?
CSRF attacks force authenticated users to submit unwanted requests.
CSRF in Templates
<form method="post">
{% csrf_token %}
<input type="text" name="data">
<button type="submit">Submit</button>
</form>
CSRF in AJAX
// Get cookie
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
// Add to headers
fetch('/api/data', {
method: 'POST',
headers: {
'X-CSRFToken': getCookie('csrftoken'),
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
Exempt Views
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_api_view(request):
# CSRF not checked
pass
Settings
CSRF_COOKIE_SECURE = True # HTTPS only
CSRF_COOKIE_HTTPONLY = True # JS inaccessible
CSRF_COOKIE_SAMESITE = 'Lax' # Same-site policy
Mini Practice
- Add CSRF token to forms
- Handle CSRF in AJAX requests
- Exempt a view from CSRF
- Configure CSRF settings
Up Next
Continue with File Upload — handling file uploads.
Related Topics
Frequently Asked Questions about CSRF
What is CSRF in Django?
CSRF is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn CSRF?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn CSRF.
Why is CSRF important in Django?
CSRF is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.