How to Fix ModuleNotFoundError: no module named ‘corsheaders’

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

  1. You have not installed a django-cors-headers package
  2. Virtual environment issues
  3. Incorrect Python environment
  4. Corrupted or failed installation
  5. Path configuration issue
  6. Naming your module corsheaders.py, which mimick the official module.

Flowchart

Flowchart of Fixing ModuleNotFoundError: no module named 'corsheaders'

 

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

Screenshot of installing 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.

Screenshot of django-cors-headers module in anaconda

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.

Github: Install the django-cors-headers using the source code

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!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.