How to handle Cross-Origin Resource Sharing (CORS) in Django?
There are typically two methods for handling cross-origin resource sharing issues in Django.
- Allow cross-origin resource sharing in Django by using the django-cors-headers package.
- Headers for enabling CORS in Django.
- configuration file
Firstly, you need to install django-cors-headers.
pip install django-cors-headers
Then configure the middleware in settings.py.
INSTALLED_APPS = [
...
'corsheaders',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
- Allow-Origin Access-Control
from django.http import JsonResponse
def my_view(request):
response = JsonResponse({'message': 'Hello, World!'})
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
response['Access-Control-Allow-Headers'] = 'Content-Type'
return response
This way, you can now handle cross-origin resource sharing issues in Django.