enable cors in django

How to Enable CORS in Django Project

Cross Origin Resource Sharing (CORS) allows your websites to accept requests from other domains. However, by default, CORS is disabled in Django for security reasons. But sometimes you may need to serve web pages and other resources to domains outside your website, especially if you are building REST APIs. In this article, we will look at how to enable CORS in Django projects.


How to Enable CORS in Django Project

Here are the steps to enable CORS in Django Project. Basically, we will use django-cors-headers package that sets a response header to allow CORS requests from other domains. Browsers use these headers to send CORS requests from clients on other websites to your websites.


1. Install django-cors-headers

django-cors-headers is a python package that manages setting of CORS headers in Django. Open terminal and run the following command to install it via pip.

$ sudo pip install django-cors-headers

If you don’t have PIP on your system, here are the steps to install PIP in Ubuntu.


2. Add corsheaders app

django-cors-headers package is referred to as corsheaders inside Django. So you need to add the corsheaders app your Django projects applications. Open settings.py file or your project. Add cors headers in INSTALLED_APPS section.

INSTALLED_APPS = [
   ...
   'corsheaders',
   ...
  ]


3. Add corsheaders middleware

Also add CorsMiddleware to settings.py as shown below.

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  ...
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'corsheaders.middleware.CorsMiddleware',
]


4. Configure CORS Access

If you need to allow CORS from all domains, set the CORS_ORIGIN_ALLOW_ALL variable to True.

CORS_ORIGIN_ALLOW_ALL = True

If you want to allow access from only specific domains, then set CORS_ORIGIN_ALLOW_ALL variable to False, and list the allowed domains in CORS_ORIGIN_WHITELIST variable. In the following example, we have allowed CORS from localhost, website1.com and even an IP address 34.32.12.34 to show that you can use a mix of IP addresses, localhost and website domains. You can even add subdomains to CORS_ORIGIN_WHITELIST if you want.

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
  'http://localhost:8000',
  'https://website1.com',
  'http://34.32.12.34'
)

Restart Django server to apply changes. That’s it. Now your website will be available from other domains. Here is the detailed documentation about django-cors-headers package.

Also read:

How to Combine Querysets in Django
How to Convert PDF to Image/JPG
How to Redirect With Query String in Apache
How to Check if Cookie is Set in Apache
How to Fix NoReverseMatch Error in Django

Leave a Reply

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