Enabling Cors — Django

Build a Product Review Backend with DRF — Part 6

Emre Cevik
Python | Django & Rest
3 min readOct 17, 2020

--

What is Cors?

Cross Origin Resource Sharing (CORS) is a security mechanism that allows a web page from one domain or origin to access a resource with a different domain. Server knows where a request is coming from and can choose whether or not to accept the request based on this.

https://drawings.jvns.ca/cors/

We can use test-cors.org for testing CORS requests.

https://www.test-cors.org

Enter your api url in “Remote URL” and submit request. When CORS not enabled, the result will look like the following

https://www.test-cors.org

We’ll use dango-cors-headers package for enabling cors.

A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.

First we need to install django-cors-headers package

After installation completes, add corsheaders INSTALLED_APPS:

We need to add a middleware class to listen in on responses. CorsMiddleware should be placed before CommonMiddleware or other middlewares which can generate responses. Open medium/settings.py file and type the following lines of code:

Configuration

CORS_ALLOWED_ORIGINS : A list of origins that are authorized to make cross-site HTTP requests.

CORS_ALLOW_ALL_ORIGINS : If True, all origins will be allowed. Setting this to True can be dangerous, as it allows any website to make cross-origin requests to yours.

CSRF_TRUSTED_ORIGINS : A list of hosts which are trusted origins for unsafe requests. If you need cross-origin unsafe requests over HTTPS, continuing the example, add “subdomain.safesite.com” to this list.

CORS_ALLOW_CREDENTIALS : If True, cookies will be allowed to be included in cross-site HTTP requests.

Detailed descriptions for django-cors-headers you can check

For enable CORS open medium/settings.py file and type the following lines of code:

We will use test-cors.org for testing CORS request again. Enter your api url in “Remote URL” and submit request.

https://www.test-cors.org

When CORS enabled you will see it below:
(XHR Status : 200)

https://www.test-cors.org

You can download part 6 files from

If you want to learn more about Django, do check out the documentation, django rest framework website and make sure to check out parts of this series!

--

--