[Django]-Import error django corsheaders

159👍

Using pip :

pip install django-cors-headers

Using pipenv :

pipenv install django-cors-headers

8👍

Step 1. Install corsheaders:

python -m pip install django-cors-headers

Step 2. Add cors-headers to INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

Step 3. Add the Cors headers middleware:

MIDDLEWARE = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...,
]

NOTE: Bear in mind that you should place the CorsMiddleware as high as possible to not be overwriten by other middleware or any behaviour caused by other middleware.

Step 4. Add cors headers in settings.py:

CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:3000',
    'http://localhost:3030',
    'yoursite.com'
]

OR

CORS_ORIGIN_WHITELIST = [
    'http://127.0.0.1:3000',
    'http://localhost:4200',
    'yoursite.com'
]

Note: Also check whether the endpoint you are requesting are within the CORS_ALLOWED_ORIGINS. Also, avoid using '*' within the same variable to avoid any security breach.

Please, check its documentation there are way more detail and links that can solve some questions you have:

https://github.com/adamchainz/django-cors-headers#setup

7👍

Try This.

pip install --user django-cors-headers

1👍

I had the same problem after I installed via pip. Then I downloaded source and manually installed the django-cors-headers after that the problem was gone.

1👍

Step 1. Install corsheaders:

python -m pip install django-cors-headers

Step 2. Add cors-headers to INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

Step 3. Add the Cors headers middleware:

MIDDLEWARE = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    ...,
]

Step 4. Add CORS_ORIGIN_WHITELIST array in settings.py:

CORS_ORIGIN_WHITELIST = [
    'http://127.0.0.1:3000',
    'http://localhost:4200',
    'http://yoursite.com'
]

0👍

You probably have a typo in your settings.

INSTALLED_APPS = [
    "corsheaders"
    
]

0👍

For anyone following Elias Prado’s answer with no success, try running your django server on a different port. For me, port 8000 was giving me issues. Probably because that’s where I run my work project. Trying port 8008 did the trick!

python3 manage.py runserver 8008

Hope this helps!

-3👍

From your traceback, it looks like you are not running the Django app in virtual environment. You could do two things:

  1. Install django-corsheaders system wide so it’s available to your app, with or without virtual environment

  2. Or you activate the virtual environment and run the django app (since you have already confirmed that django-corsheaders is installed in virtual environment.)

👤avi

-4👍

You don’t need to install anything, just use runserver:

python manage.py runserver

Leave a comment