“No ‘Access-Control-Allow-Origin’ header is present on the requested resource” in django

Here’s what I did when I got the same error from Django Rest Framework while sending an API request from Restangular.
What this does is add CORS (Cross-Origin Resource Sharing) headers to responses from Django Rest Framework. Not having CORS headers was the cause of the error.

In the Django Project root folder (where the manage.py file is located), do:

pip install django-cors-headers

I tried it using virtualenv but was not able to get it to work, so I installed it without switching to virtualenv and got it installed.

After installing it, you have to make some edits to your django settings.py

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

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

CORS_ORIGIN_ALLOW_ALL = True   

Setting above to true allows all origins to be accepted.

References: https://github.com/ottoyiu/django-cors-headers

Leave a Comment