CORS on Django REST Framework

In the post Django REST Framework: API in a few minutes in Python, I showed you how to build your very first API in Python.

But there is one minor problem, if you test your API with another application, like an Angular or React frontend, you are going to face CORS problems.

To solve this you can install the django-cors-headers in your app using pip.

pip install django-cors-headers

After installing the django-cors-headers in your project, you have to configure it in the settings.py file, including the corsheaders in the INSTALLED_APPS.

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

The end result will look like this.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
]

After that, still in settings.py, add the corsheaders.middleware.CorsMiddleware in MIDDLEWARE before any middleware that can generate responses like CommonMiddleware.

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

The end result will look like this.

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

Finally, you have to add a new block in the settings.py file that contains the list of allowed origins, that is, those who can consume the API.

In the example below I am including http://localhost:4200 which is Angular’s default localhost.

CORS_ORIGIN_WHITELIST = [
    "http://localhost:4200",
]