Robert's Homepage

How to Add CORS to Django

#django #how-to #python

First, use django-cors-headers, whose documentation says to install the library

python -m pip install django-cors-headers

then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...,
]

See the configuration section of its documentation, paying particular attention to the various CORS_ORIGIN_ settings. You’ll need to set some of those based on your needs.

CORS_ALLOWED_ORIGINS = [
    "http://localhost:<FRONTENDPORT>",
]