How To Allow CORS For Specific Domain in Django

April 10, 2016

CORS is a mechanism that allows resource like JS, CSS, etc. on a web page to be requested from another time. Almost every website will have the **same-origin policy **meaning that those resources can be accessed ONLY from their domain name.

Let’s talk about a loosely coupled web app scenario.

So when we try to make AJAX call from our front end it’ll usually through a CORS error. We can use Chrome extension like Allow CORS: Access-Control-Allow-Origin to bypass that CORS same origin policy.

But in a production environment, we need to ALLOW our frontend domain address.

In Django, we can easily to it in just 4 steps

Step #1

Install the django-cors-headers

pip install django-cors-headers

Step #2

Then add it to your installed apps. Basically, open the of your app and you will find **INSTALLED_APPS **array. Just add corsheaders in it just like this


Step #3

Just like INSTALLEDAPP you need to add it in **MIDDLEWARECLASSES**


Make sure to place it before Django’s CommonMiddleware

Step #4

Now we are going to configure CORS policy of the app.



That’s all… You can now access resource from your backend.

👋 I'm Ashik Nesin • Principal Software Engineer @Chargebee 👨‍💻• I write about web development & behinds the scenes of startup/side projects that I'm building

© 2022 Nesin Technologies LLP