How to add CORS Headers to Django responses

Browsers by default do not allow Cross Origin Requests for security reasons. A Cross Origin Request occurs when a script on one domain attempts to get data from a different domain. Cross-Origin Resource Sharing (CORS)is a mechanism that tells web browsers to give an application in one domain access to selected resources from a different domain. When building APIs it is important to be mindful of CORS and enable it in your Django application.

The easiest way to enable CORS in Django is through a package known as django-cors-headers. This package adds CORS Headers to responses. To install django-cors-headers, run the following command in a terminal:

pip install django-cors-headers

Once it is installed, add it to your Django application’s installed apps section in the file:


Next, add a middleware class to listen in on responses:


The 'corsheaders.middleware.CorsMiddleware', should be placed as high as possible in the MIDDLEWARE list before any middleware that generates responses.

Next, configure what domains are whitelisted to use CORS:


2 comments on “How to add CORS Headers to Django responsesAdd yours →

Leave a Reply

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