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

Fix CORS Error: Access to XMLHttpRequest at 'https://api.example.com/data/' from origin 'https://app.example.com' has been blocked by CORS policy. in Django

This error means the browser blocked a cross-origin request because the Django backend did not include the correct CORS headers. Fix it by installing django-cors-headers, adding it to INSTALLED_APPS and MIDDLEWARE, and configuring CORS_ALLOWED_ORIGINS with the frontend's domain in settings.py.

Reading the Stack Trace

Browser Console Error: Access to XMLHttpRequest at 'https://api.example.com/data/' from origin 'https://app.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Network Tab: Request URL: https://api.example.com/data/ Request Method: OPTIONS Status Code: 403 Forbidden Response Headers: Content-Type: text/html # Missing: Access-Control-Allow-Origin Django Server Log: [10/Apr/2026 14:55:02] "OPTIONS /data/ HTTP/1.1" 403 0

Here's what each line means:

Common Causes

1. django-cors-headers not installed

The django-cors-headers package is not installed or not configured, so Django does not add CORS response headers.

# settings.py — no CORS configuration
INSTALLED_APPS = [
    'django.contrib.admin',
    'rest_framework',
    # Missing: 'corsheaders'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    # Missing: 'corsheaders.middleware.CorsMiddleware'
]

2. CORS middleware in wrong position

CorsMiddleware is placed after CommonMiddleware, so it does not process the response before other middleware blocks it.

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.common.CommonMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # Too late in the chain
]

3. Frontend origin not in allowed list

The frontend domain is not included in CORS_ALLOWED_ORIGINS, so the CORS middleware rejects it.

# settings.py
CORS_ALLOWED_ORIGINS = [
    'https://old-frontend.example.com',  # New frontend not listed
]

The Fix

Install django-cors-headers and add CorsMiddleware before CommonMiddleware in MIDDLEWARE. List all allowed frontend origins in CORS_ALLOWED_ORIGINS. Never use CORS_ALLOW_ALL_ORIGINS = True in production as it allows any website to make requests to your API.

Before (broken)
# settings.py — no CORS configuration
INSTALLED_APPS = [
    'django.contrib.admin',
    'rest_framework',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.common.CommonMiddleware',
]
After (fixed)
# pip install django-cors-headers

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'corsheaders',  # Added
    'rest_framework',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # Must be before CommonMiddleware
    'django.middleware.common.CommonMiddleware',
]

CORS_ALLOWED_ORIGINS = [
    'https://app.example.com',
    'http://localhost:3000',  # Development
]

# Optional: allow specific headers and methods
CORS_ALLOW_HEADERS = [
    'accept',
    'authorization',
    'content-type',
    'x-csrftoken',
]

CORS_ALLOW_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS',
]

Testing the Fix

import pytest
from django.test import TestCase, Client


class TestCORSHeaders(TestCase):
    def test_cors_headers_on_allowed_origin(self):
        response = self.client.options(
            '/api/data/',
            HTTP_ORIGIN='https://app.example.com',
            HTTP_ACCESS_CONTROL_REQUEST_METHOD='GET',
        )
        assert response.get('Access-Control-Allow-Origin') == 'https://app.example.com'

    def test_cors_headers_missing_for_disallowed_origin(self):
        response = self.client.options(
            '/api/data/',
            HTTP_ORIGIN='https://evil.example.com',
            HTTP_ACCESS_CONTROL_REQUEST_METHOD='GET',
        )
        assert response.get('Access-Control-Allow-Origin') is None

    def test_preflight_returns_200(self):
        response = self.client.options(
            '/api/data/',
            HTTP_ORIGIN='https://app.example.com',
            HTTP_ACCESS_CONTROL_REQUEST_METHOD='POST',
            HTTP_ACCESS_CONTROL_REQUEST_HEADERS='content-type',
        )
        assert response.status_code == 200

    def test_get_request_includes_cors_header(self):
        response = self.client.get(
            '/api/data/',
            HTTP_ORIGIN='https://app.example.com',
        )
        assert response.get('Access-Control-Allow-Origin') == 'https://app.example.com'

Run your tests:

pytest

Pushing Through CI/CD

git checkout -b fix/cors-headers-config,git add settings.py requirements.txt,git commit -m "fix: install and configure django-cors-headers for frontend access",git push origin fix/cors-headers-config

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: 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 CORS header tests.
  2. Open a pull request with the CORS configuration 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 cross-origin requests work in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates tests for both allowed and disallowed origins, and validates that preflight requests 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. It allows any website to make authenticated requests to your API. Only use it in development. In production, always list specific allowed origins.

POST requests with JSON content type trigger a preflight OPTIONS request. Ensure CorsMiddleware handles OPTIONS and that your allowed headers include 'content-type'.