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
- On the first visit, Django sets a
csrftokencookie - Every HTML form with POST must include a hidden field containing the token
- Django compares the token from the form with the token in the cookie
- 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.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!