How to Resolve Python "`ModuleNotFoundError: No module named 'corsheaders'"
When developing web applications with Django, especially APIs, you'll often need to handle Cross-Origin Resource Sharing (CORS). The popular django-cors-headers
library facilitates this. Encountering the ModuleNotFoundError: No module named 'corsheaders'
means that Python cannot find this necessary library when trying to run your Django application, typically because it hasn't been installed in the correct environment or configured properly within your Django project.
This guide provides a comprehensive solution, covering installation, Django settings configuration, and environment verification.
Understanding the Error: Missing Django App
The ModuleNotFoundError
is Python's standard way of saying it searched its known paths but couldn't locate the specified module (corsheaders
in this case). Within a Django project, this usually means the required third-party package providing this module is either missing from the Python environment or not correctly registered within the Django application itself.
Common Causes
- Package Not Installed: The
django-cors-headers
package was never installed. - Incorrect Environment: The package was installed in a different Python environment (e.g., globally) than the one your Django project/server is currently using (e.g., a virtual environment).
- Virtual Environment Not Activated: Forgetting to activate the virtual environment before installing or running the Django server.
- Missing Django Configuration: The
corsheaders
app wasn't added toINSTALLED_APPS
or the middleware wasn't added toMIDDLEWARE
in your Djangosettings.py
. - IDE Misconfiguration: Your IDE (VS Code, PyCharm) might be pointing to the wrong Python interpreter.
- Filename Shadowing: You have a file named
corsheaders.py
in your project, conflicting with the library.
Solution 1: Install django-cors-headers
Package
First, ensure the package is installed in the correct environment. Activate your project's virtual environment if you're using one, then run the installation command.
- Using
pip
:pip install django-cors-headers
# Or explicitly with python/pip3
python -m pip install django-cors-headers
pip3 install django-cors-headers
# If permission issues arise (less likely in venv)
pip install django-cors-headers --user
sudo pip3 install django-cors-headers # Avoid if possible, use venv - Using
conda
(Anaconda environments):# conda-forge channel is often recommended
conda install -c conda-forge django-cors-headers
Solution 2: Configure Django settings.py
After installing the package, you MUST register it with your Django project.
Add to INSTALLED_APPS
Open your project's settings.py
file and add "corsheaders"
to the INSTALLED_APPS
list. Make sure to include the trailing comma, as omitting it can sometimes lead to import errors.
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# ... other apps
'corsheaders', # ✅ Add this line
# ... your apps
]
Add to MIDDLEWARE
(Correct Order)
You also need to add the CORS middleware to handle the necessary headers. Its position in the MIDDLEWARE
list is important. It should be placed high up, generally before middleware that might generate responses, like CommonMiddleware
.
# settings.py
MIDDLEWARE = [
# Place CORS Middleware high, before CommonMiddleware usually
'corsheaders.middleware.CorsMiddleware', # ✅ Add this line
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware', # CORS Middleware before this
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# ... other middleware
]
If using CORS_REPLACE_HTTPS_REFERER = True
, place CorsMiddleware even higher, potentially before CsrfViewMiddleware depending on your needs.
Consult the django-cors-headers documentation for specific placement advice.
After modifying settings.py
, make sure to restart your Django development server for the changes to take effect.
Solution 3: Verify the Python Environment
Ensure consistency between where you installed the package and where Django is running.
- Check Python Version: Use
python --version
orpython3 --version
. - Use Virtual Environments (Recommended): Always work within an activated virtual environment (
venv
orconda env
) for your Django projects. Install packages after activating the environment.- Create:
python3 -m venv venv
- Activate:
source venv/bin/activate
(Linux/macOS) orvenv\Scripts\activate
(Windows) - Install:
pip install django-cors-headers
- Create:
- Check IDE Interpreter Settings: In VS Code or PyCharm, ensure the selected Python interpreter for the project points to the Python executable inside your virtual environment.
Solution 4: Check for Filename/Variable Shadowing
Do not name any of your project files corsheaders.py
. Avoid using corsheaders
as a variable name in the scope where you import the module. Rename any conflicting files or variables.
Debugging Steps
- Check Installation (
pip show
): Activate your environment and runpip show django-cors-headers
. Verify it's installed and check theLocation
. - Restart Server / IDE: Stop and restart the Django development server (
manage.py runserver
). Sometimes restarting the IDE (VS Code, PyCharm) can also help clear cached states. - Reinstall / Upgrade Package:
pip uninstall django-cors-headers
pip install django-cors-headers
# Or upgrade
pip install --upgrade django-cors-headers
Platform/Tool Specific Installation Guides
These sections repeat the core pip install django-cors-headers
or conda install ... django-cors-headers
commands, tailored for clarity within each environment. Refer to Solution 1 for the various command options.
- Install on Windows: Use Command Prompt or PowerShell (potentially as Admin or using
--user
). Considervenv
. - Install on macOS or Linux: Use Terminal. Use
pip3
. Considervenv
or--user
orsudo
(last resort). - Install in Visual Studio Code: Use the integrated terminal, ensuring the correct venv is active.
- Install in PyCharm: Use the integrated terminal (check venv) or the PyCharm package management UI (
Settings
>Project
>Python Interpreter
>+
). - Install in Anaconda: Activate conda environment. Use
conda install -c conda-forge django-cors-headers
orpip install django-cors-headers
. - Install in Jupyter Notebook (Less Common for Django): Use
!pip install django-cors-headers
in a cell and restart the kernel. (Note: Running full Django projects directly within a standard Jupyter Notebook is unusual).
Remember to configure INSTALLED_APPS
and MIDDLEWARE
in settings.py
after installing via any method.
Conclusion
The ModuleNotFoundError: No module named 'corsheaders'
in a Django project typically means the django-cors-headers
package is either:
- Not installed in the active Python environment.
- Installed in the wrong environment.
- Not configured correctly in Django's
settings.py
.
The primary solution involves:
- Activating the correct virtual environment.
- Installing the package using
pip install django-cors-headers
(orconda
). - Adding
'corsheaders'
toINSTALLED_APPS
. - Adding
'corsheaders.middleware.CorsMiddleware'
toMIDDLEWARE
(in the correct order). - Restarting the Django server.
- Ensuring your IDE uses the correct interpreter.
Following these steps systematically should resolve the error and allow you to use django-cors-headers
in your project.