Django cors
django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS). Adding CORS headers allows your resources to be accessed on other domains.
CORS is a mechanism to allow interaction with resources hosted on different domains.
and then add it to your installed apps:
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE = [
...,
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
...,
]
CorsMiddleware
should be placed as high as possible, especially before any middleware that can generate responses such as Django’s CommonMiddleware
or Whitenoise’s WhiteNoiseMiddleware
. If it is not before, it will not be able to add the CORS headers to these responses.
Configuration
Configure the middleware’s behaviour in your Django settings. You must set at least one of three following settings:
CORS_ALLOWED_ORIGINS
CORS_ALLOWED_ORIGIN_REGEXES
CORS_ALLOW_ALL_ORIGINS
Example:
CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000",
]
CORS_ORIGIN_WHITELIST Deprecated
VS CORS_ALLOWED_ORIGINS
- before version
3.0.0
he setting used to whitelist allowed origins wasCORS_ORIGIN_WHITELIST
. - In version
3.0.0
and later, the naming convention was changed toCORS_ALLOWED_ORIGINS
for consistency with other Django settings. - You should use
CORS_ALLOWED_ORIGINS
in more recent versions ofdjango-cors-headers
:
Reference
- django-cors-headers
- Django CORS Guide
- Using React with Django to create an app
- How to Integrate React and Django framework, in a simpler way
- what are the possible ways to integrate react: reddit
- How to build a React application in a Django project
- Integrating Django with Reactjs using Django REST Framework