ModuleNotFoundError: no module named ‘corsheaders’ error occurs when django-cors-headers is not installed, or its path is misconfigured. To fix this error, install the ‘django-cors-headers’ package.
Common causes of the error
- You have not installed a django-cors-headers package
- Virtual environment issues
- Incorrect Python environment
- Corrupted or failed installation
- Path configuration issue
- Naming your module corsheaders.py, which mimick the official module.
Flowchart
Solution 1: Install the django-cors-headers
Here is the command to install the django-cors-headers using this command:
pip install django-cors-headers
Solution 2: Install the django-cors-headers using conda
You can use the conda package manager with Anaconda distribution to install the django-cors-headers module.
conda install -c conda-forge django-cors-headers
The above command is for installing the django-cors-headers package using the conda package manager.
The conda-forge is the channel or repository where the package is hosted.
To run this command, add conda and the conda-forge channel to your system’s PATH.
It will download and install the latest version of the django-cors-headers package.
After the installation, you can import and use it in your Django project.
Solution 3: Install the django-cors-headers using the source code
If you are using Git to install the package, go to this link and pull the package into your project.
It adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.
You can check if your django-cors-headers is installed on your computer by typing this command:
pip show django-cors-headers
If you have already installed the django-cors-headers module, add it to your installed apps:
In your settings.py, add below code:
INSTALLED_APPS = [
#
"corsheaders",
#
]
Make sure to add a comma at the end to not cause an error problem like “ModuleNotFoundError. “
Also, add this to your middleware class in settings.py:
MIDDLEWARE = [ # "corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
# ]
That’s all!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.