Fix Forbidden (403): CSRF verification failed. Request aborted. in Django
This error means Django's CSRF protection rejected a POST request because the CSRF token was missing or invalid. Fix it by including {% csrf_token %} in your form template, ensuring the CSRF middleware is active, and for AJAX requests, sending the token in the X-CSRFToken header extracted from the csrftoken cookie.
Reading the Stack Trace
Here's what each line means:
- File "/venv/lib/python3.11/site-packages/django/middleware/csrf.py", line 385, in process_view: Django's CSRF middleware intercepts every POST request and validates the CSRF token before the view runs.
- File "/venv/lib/python3.11/site-packages/django/middleware/csrf.py", line 322, in _check_token: The token check failed because no valid CSRF token was found in the request body or headers.
- raise PermissionDenied('CSRF verification failed. Request aborted.'): Django returns a 403 Forbidden response to prevent potential cross-site request forgery attacks.
Common Causes
1. Missing {% csrf_token %} in form template
The HTML form does not include the CSRF token template tag, so Django has no token to validate.
<!-- templates/contact.html -->
<form method="post" action="/contact/">
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
2. AJAX POST without CSRF header
JavaScript sends a POST request without including the X-CSRFToken header.
fetch('/api/submit/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'hello' }),
});
3. CSRF_TRUSTED_ORIGINS missing in production
In Django 4+, POST requests from a different origin require the domain to be in CSRF_TRUSTED_ORIGINS.
# settings.py
ALLOWED_HOSTS = ['myapp.example.com']
# Missing: CSRF_TRUSTED_ORIGINS = ['https://myapp.example.com']
The Fix
Add {% csrf_token %} inside every form that uses method POST. For AJAX requests, extract the CSRF token from the csrftoken cookie and send it in the X-CSRFToken header. In production with Django 4+, also add your domain to CSRF_TRUSTED_ORIGINS.
<!-- templates/contact.html -->
<form method="post" action="/contact/">
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
<!-- templates/contact.html -->
<form method="post" action="/contact/">
{% csrf_token %}
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
<!-- For AJAX requests, add this JavaScript -->
<script>
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;
}
fetch('/api/submit/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken'),
},
body: JSON.stringify({ message: 'hello' }),
});
</script>
Testing the Fix
import pytest
from django.test import TestCase, Client
class TestCSRFProtection(TestCase):
def setUp(self):
self.client = Client(enforce_csrf_checks=True)
def test_post_without_csrf_token_returns_403(self):
response = self.client.post('/contact/', {'message': 'hello'})
assert response.status_code == 403
def test_post_with_csrf_token_succeeds(self):
# Use the regular client which includes CSRF token automatically
client = Client()
response = client.get('/contact/')
assert response.status_code == 200
response = client.post('/contact/', {'message': 'hello'})
assert response.status_code in (200, 302)
def test_form_template_contains_csrf_token(self):
client = Client()
response = client.get('/contact/')
self.assertContains(response, 'csrfmiddlewaretoken')
Run your tests:
pytest
Pushing Through CI/CD
git checkout -b fix/csrf-token-missing,git add templates/contact.html settings.py,git commit -m "fix: add CSRF token to form and configure trusted origins",git push origin fix/csrf-token-missing
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
- run: pip install -r requirements.txt
- run: python manage.py check --deploy
- run: pytest --tb=short -q
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
pip install bugstack
Step 2: Initialize
import bugstack
bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the full test suite locally including CSRF enforcement tests.
- Open a pull request with the template and settings changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify CSRF-protected forms work correctly in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite with CSRF enforcement enabled, generates additional security tests, and validates that form submissions succeed before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
No. The @csrf_exempt decorator disables CSRF protection entirely for that view, which creates a security vulnerability. Only use it for API endpoints that use token-based authentication instead.
Yes. DRF's SessionAuthentication enforces CSRF, but TokenAuthentication and JWT do not require it. If your API uses token auth, CSRF is not needed for those endpoints.