Categories
Python Answers

How to enable CORS on Python Django REST Framework?

Spread the love

Sometimes, we want to enable CORS on Python Django REST Framework

In this article, we’ll look at how to enable CORS on Python Django REST Framework.

How to enable CORS on Python Django REST Framework?

To enable CORS on Python Django REST Framework, we use the django-cors-headers package.

To install it, we run

python -m pip install django-cors-headers

Then we use it by writing

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

in settings.py.

And we add the middleware by writing

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

And we add the domains that we allow CORS from with

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3030',
]

Conclusion

To enable CORS on Python Django REST Framework, we use the django-cors-headers package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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