How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Django · Python

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

Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/venv/lib/python3.11/site-packages/django/middleware/csrf.py", line 458, in _reject raise RejectRequest(reason) File "/venv/lib/python3.11/site-packages/django/middleware/csrf.py", line 385, in process_view self._check_token(request) File "/venv/lib/python3.11/site-packages/django/middleware/csrf.py", line 322, in _check_token raise InvalidToken('CSRF token missing.') django.middleware.csrf.InvalidToken: CSRF token missing. During handling of the above exception, another exception occurred: File "/venv/lib/python3.11/site-packages/django/middleware/csrf.py", line 460, in _reject return self._get_failure_view()(request, reason=reason) File "/venv/lib/python3.11/site-packages/django/views/csrf.py", line 28, in csrf_failure raise PermissionDenied('CSRF verification failed. Request aborted.') django.core.exceptions.PermissionDenied: CSRF verification failed. Request aborted.

Here's what each line means:

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.

Before (broken)
<!-- templates/contact.html -->
<form method="post" action="/contact/">
  <input type="text" name="message" />
  <button type="submit">Send</button>
</form>
After (fixed)
<!-- 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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run the full test suite locally including CSRF enforcement tests.
  2. Open a pull request with the template and settings changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.