How to enable CORS on Django REST Framework?

 If we are building an API layer using the Django REST framework and accessing these APIs in the front-end application we need to enable the CORS on Django Rest Framework otherwise we will get an error “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite

In this tutorial, we will look at how to enable CORS on the Django REST framework with examples.

How to enable CORS on Django REST Framework?

CORS stands for Cross-Origin Resource Sharing. It is an HTTP-header-based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts that are present in the front-end application. Adding CORS headers allows your resources to be accessed on other domains

So if we have to allow the Django REST API to be accessed from the other front-end application which is hosted on a different domain we need to enable CORS(Cross-Origin Resource Sharing).

The easiest way to enable CORS on the Django REST framework is by installing a library django-cors-headers.

Step 1 – Install the django-cors-headers using pip

python -m pip install django-cors-headers

Step 2 – Open the settings.py file and add the CORS headers to your installed apps as shown below.

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

Step 3 – Add the CORS middlewares classes in the settings.py Middleware section as shown below.

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

Step 4 – The last step is to allow the domain which needs to access the API. 

You can allow all the domains to access the API by setting CORS_ORIGIN_ALLOW_ALL=True 

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

It is not recommended to allow all the domains as it will increase the security risk and we should only allow only the domains that need access to this API.

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

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

You can also allow which HTTP methods can be accessed by providing the list of HTTP verbs as shown below.

CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like