Skip to content

Django cors

django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS). Adding CORS headers allows your resources to be accessed on other domains.

CORS is a mechanism to allow interaction with resources hosted on different domains.

$ pip install django-cors-headers

$ pip install django djangorestframework django-cors-headers

and 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",
    ...,
]

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django’s CommonMiddleware or Whitenoise’s WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

Configuration

Configure the middleware’s behaviour in your Django settings. You must set at least one of three following settings:

  • CORS_ALLOWED_ORIGINS
  • CORS_ALLOWED_ORIGIN_REGEXES
  • CORS_ALLOW_ALL_ORIGINS

Example:

CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000",
]

CORS_ORIGIN_WHITELIST Deprecated VS CORS_ALLOWED_ORIGINS

  • before version 3.0.0 he setting used to whitelist allowed origins was CORS_ORIGIN_WHITELIST.
  • In version 3.0.0 and later, the naming convention was changed to CORS_ALLOWED_ORIGINS for consistency with other Django settings.
  • You should use CORS_ALLOWED_ORIGINS in more recent versions of django-cors-headers:

Reference