close

[Solved] import django corsheaders

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error import django corsheaders in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How import django corsheaders Error Occurs?

Today I get the following error import django corsheaders in python.

How To Solve import django corsheaders Error ?

  1. How To Solve import django corsheaders Error ?

    To Solve import django corsheaders Error The link you referenced in your question recommends using django-cors-headers, whose documentation says to install the library

  2. import django corsheaders

    To Solve import django corsheaders Error The link you referenced in your question recommends using django-cors-headers, whose documentation says to install the library

Solution 1


The link you referenced in your question recommends using django-cors-headers, whose documentation says to install the library

python -m pip install django-cors-headers

and then add it to your installed apps:

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

You will also need to add a middleware class to listen in on responses:

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

and specify domains for CORS, e.g.:

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3030',
]

Please browse the configuration section of its documentation, paying particular attention to the various CORS_ORIGIN_ settings. You’ll need to set some of those based on your needs.

Solution 2


You can do by using a custom middleware, even though knowing that the best option is using the tested approach of the package django-cors-headers. With that said, here is the solution:

create the following structure and files:

— myapp/middleware/__init__.py

from corsMiddleware import corsMiddleware

— myapp/middleware/corsMiddleware.py

class corsMiddleware(object):
    def process_response(self, req, resp):
        resp["Access-Control-Allow-Origin"] = "*"
        return resp

add to settings.py the marked line:

MIDDLEWARE_CLASSES = (
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",

    # Now we add here our custom middleware
     'app_name.middleware.corsMiddleware' <---- this line
)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read