How to enable CORS headers in Django

In this, we will discuss how to enable CORS headers in Django.

What is CORS?

CORS stands for Cross-Origin Resource Sharing.

CORS is a mechanism that enables interaction with resources hosted across domains.  It allows our website to accept requests from our domains.

CORS is disabled in Django so we have to enable it.

Steps to enable CORS header

It is very easy to enable the CORS header in Django because it is a web framework.

  1. Install django-cors-headers
  2. Add to Installed Apps
  3. Add Middleware class
  4. Configure domains

Step 1 – Installation:

To install this run the below command in your terminal:

pip install django-cors-headers

Step 2- Add to Installed Apps:

After it is installed we have to add it in Installed Apps in settings.py like this.

INSTALLED_APPS = [

    ...


    'corsheaders',     

    ...

]

Step 3- Add Middleware:

After adding in installed apps we have to add a middleware in settings.py so to do so type the below code in middleware in settings.py.

MIDDLEWARE = [

    'corsheaders.middleware.CorsMiddleware'

    'django.middleware.security.SecurityMiddleware',

    'django.contrib.sessions.middleware.SessionMiddleware',

    ...

]

Step 4 – Configure CORS

If we want to allow access to all domains simply we can set the variable to TRUE in settings.py.

CORS_ORIGIN_ALLOW_ALL = True

 

But if want to allow access to a specific domain we can do this.

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
  'http://localhost:8000',
)

To apply changes we need to restart the Django server.

Thank You.

Also read: Exclude one or multiple objects from Django Queryset

Leave a Reply

Your email address will not be published.