Skip to main content

django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).

Project description pre-commit

A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.

Improve your Django and Git skills with my books.

About CORS

Adding CORS headers allows your resources to be accessed on other domains. It’s important you understand the implications before adding the headers, since you could be unintentionally opening up your site’s private data to others.

Some good resources to read on the subject are:


Python 3.8 to 3.12 supported.

Django 3.2 to 5.0 supported.


Install from pip:

python -m pip install django-cors-headers

and then add it to your installed apps:


Make sure you add the trailing comma or you might get a ModuleNotFoundError (see this blog post).

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


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.


django-cors-headers was created in January 2013 by Otto Yiu. It went unmaintained from August 2015 and was forked in January 2016 to the package django-cors-middleware by Laville Augustin at Zeste de Savoir. In September 2016, Adam Johnson, Ed Morley, and others gained maintenance responsibility for django-cors-headers (Issue 110) from Otto Yiu. Basically all of the changes in the forked django-cors-middleware were merged back, or re-implemented in a different way, so it should be possible to switch back. If there’s a feature that hasn’t been merged, please open an issue about it.

django-cors-headers has had 40+ contributors in its time; thanks to every one of them.


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





A list of origins that are authorized to make cross-site HTTP requests. The origins in this setting will be allowed, and the requesting origin will be echoed back to the client in the access-control-allow-origin header. Defaults to [].

An Origin is defined by the CORS RFC Section 3.2 as a URI scheme + hostname + port, or one of the special values 'null' or 'file://'. Default ports (HTTPS = 443, HTTP = 80) are optional.

The special value null is sent by the browser in “privacy-sensitive contexts”, such as when the client is running from a file:// domain. The special value file:// is sent accidentally by some versions of Chrome on Android as per this bug.



Previously this setting was called CORS_ORIGIN_WHITELIST, which still works as an alias, with the new name taking precedence.

CORS_ALLOWED_ORIGIN_REGEXES: Sequence[str | Pattern[str]]

A list of strings representing regexes that match Origins that are authorized to make cross-site HTTP requests. Defaults to []. Useful when CORS_ALLOWED_ORIGINS is impractical, such as when you have a large number of subdomains.



Previously this setting was called CORS_ORIGIN_REGEX_WHITELIST, which still works as an alias, with the new name taking precedence.


If True, all origins will be allowed. Other settings restricting allowed origins will be ignored. Defaults to False.

Setting this to True can be dangerous, as it allows any website to make cross-origin requests to yours. Generally you’ll want to restrict the list of allowed origins with CORS_ALLOWED_ORIGINS or CORS_ALLOWED_ORIGIN_REGEXES.

Previously this setting was called CORS_ORIGIN_ALLOW_ALL, which still works as an alias, with the new name taking precedence.

The following are optional settings, for which the defaults probably suffice.

CORS_URLS_REGEX: str | Pattern[str]

A regex which restricts the URL’s for which the CORS headers will be sent. Defaults to r'^.*$', i.e. match all URL’s. Useful when you only need CORS on a part of your site, e.g. an API at /api/.


CORS_URLS_REGEX = r"^/api/.*$"


A list of HTTP verbs that are allowed for the actual request. Defaults to:


The default can be imported as corsheaders.defaults.default_methods so you can just extend it with your custom methods. This allows you to keep up to date with any future changes. For example:

from corsheaders.defaults import default_methods



The list of non-standard HTTP headers that you permit in requests from the browser. Sets the Access-Control-Allow-Headers header in responses to preflight requests. Defaults to:


The default can be imported as corsheaders.defaults.default_headers so you can extend it with your custom headers. This allows you to keep up to date with any future changes. For example:

from corsheaders.defaults import default_headers



The list of extra HTTP headers to expose to the browser, in addition to the default safelisted headers. If non-empty, these are declared in the access-control-expose-headers header. Defaults to [].


The number of seconds the browser can cache the preflight response. This sets the access-control-max-age header in preflight responses. If this is 0 (or any falsey value), no max age header will be sent. Defaults to 86400 (one day).

Note: Browsers send preflight requests before certain “non-simple” requests, to check they will be allowed. Read more about it in the CORS MDN article.


If True, cookies will be allowed to be included in cross-site HTTP requests. This sets the Access-Control-Allow-Credentials header in preflight and normal responses. Defaults to False.

Note: in Django 2.1 the SESSION_COOKIE_SAMESITE setting was added, set to 'Lax' by default, which will prevent Django’s session cookie being sent cross-domain. Change the setting to 'None' if you need to bypass this security restriction.


If True, allow requests from sites on “public” IP to this server on a “private” IP. In such cases, browsers send an extra CORS header access-control-request-private-network, for which OPTIONS responses must contain access-control-allow-private-network: true.

Refer to:

CSRF Integration

Most sites will need to take advantage of the Cross-Site Request Forgery protection that Django offers. CORS and CSRF are separate, and Django has no way of using your CORS configuration to exempt sites from the Referer checking that it does on secure requests. The way to do that is with its CSRF_TRUSTED_ORIGINS setting. For example:




If you have a use case that requires more than just the above configuration, you can attach code to check if a given request should be allowed. For example, this can be used to read the list of origins you allow from a model. Attach any number of handlers to the check_request_enabled Django signal, which provides the request argument (use **kwargs in your handler to protect against any future arguments being added). If any handler attached to the signal returns a truthy value, the request will be allowed.

For example you might define a handler like this:

# myapp/
from corsheaders.signals import check_request_enabled

from myapp.models import MySite

def cors_allow_mysites(sender, request, **kwargs):
    return MySite.objects.filter(host=request.headers["origin"]).exists()


Then connect it at app ready time using a Django AppConfig:

# myapp/

default_app_config = "myapp.apps.MyAppConfig"
# myapp/

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = "myapp"

    def ready(self):
        # Makes sure all signal handlers are connected
        from myapp import handlers  # noqa

A common use case for the signal is to allow all origins to access a subset of URL’s, whilst allowing a normal set of origins to access all URL’s. This isn’t possible using just the normal configuration, but it can be achieved with a signal handler.

First set CORS_ALLOWED_ORIGINS to the list of trusted origins that are allowed to access every URL, and then add a handler to check_request_enabled to allow CORS regardless of the origin for the unrestricted URL’s. For example:

# myapp/
from corsheaders.signals import check_request_enabled

def cors_allow_api_to_everyone(sender, request, **kwargs):
    return request.path.startswith("/api/")


Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-cors-headers-4.3.1.tar.gz (21.1 kB view hashes)

Uploaded source

Built Distribution

django_cors_headers-4.3.1-py3-none-any.whl (12.8 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page