How to Fix Django CORS Error

DZone 's Guide to

How to Fix Django CORS Error

Fix Django Cors error using django-cors-headers

· Web Dev Zone ·
Free Resource

One of the common errors we get each time when we consume Django API is CORS error.
The error might say something like: Access to XMLHttpRequest at 'url’' from origin  has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Django comes with a bunch of securities. CORS (Cross-origin resource sharing) permission requirest is one of them.  A request for a resource outside of the origin is known as a cross-origin request. The web page from outside the domain is requesting Django to share its resources. And Django is not giving permission.

i.e. Access to Django page and resource has blocked by CORS policy.

Now, let's see how to give a permission and solve the error in Just 4 steps:

Step 1 - Install django-cors-headers



pip install django-cors-headers

Step 2 - Add corsheader  to the Installed App list in settings.py 


Step 3 -  Add CorsMiddleware to middleware list in settings.py


Step 4 - You have two alternatives here. Either follow Option A or Option B

Step 4 ( Option A) - Allow access to all domains by just Adding the following variables in settings.py:


Step 4 ( Option B) - Do not allow access to all the domains, but the one which you are consuming the API. Add following variables in settings.py


You are good to go now. Thanks for reading

cors, cors enabled, django, drf, error, python, rest api

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}