Published on

How To Allow CORS For Specific Domain in Django

Authors

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.

  • You have a backend (API) at http://api.example.com
  • And your frontend at http://example.com

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 settings.py of your app and you will find **INSTALLED_APPS **array. Just add corsheaders in it just like this

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

Step #3

Just like INSTALLED_APP you need to add it in MIDDLEWARE_CLASSES

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

Make sure to place it before Django's CommonMiddleware

Step #4

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

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
        'www.example.com',
        'example.com'
)

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