Handling Cors in django application
147
Introduction
CORS is a security mechanism implemented by web browsers to restrict web pages from making requests to a different domain than the one that served the page. This prevents malicious scripts from stealing data or performing unauthorized actions on other websites. Django provides built-in functionalities and popular third-party libraries to handle CORS configurations effectively.
Prerequisites
Before we delve into the steps, ensure you have the following:
- Django Project: A Django project set up and ready for development.
Step1: Installation
We would be using the django-cors-headers library. To install it, run the command below
pip install django-cors-headers
Step 2: Configuration
add "corsheaders" to your installed apps in your settings.py
INSTALLED_APPS = [
#other apps
"corsheaders"
]
Add "corsheaders.middleware.CorsMiddleware" to the top of your MIDDLEWARE list
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
#other middlewares
]
Finally, whitelist the domains in your settings.py
CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000",
]
If you want to allow all reqquests, you can use
CORS_ORIGIN_ALLOW_ALL = True
Conclusion
By effectively handling CORS in your Django application, you can securely share resources with other domains while maintaining security.
References
https://pypi.org/project/django-cors-headers/