How can I enable CORS on Django REST Framework How can I enable CORS on Django REST Framework python python

How can I enable CORS on Django REST Framework


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',    ...,]

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.


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',    ...,]CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effectCORS_ALLOW_CREDENTIALS = TrueCORS_ALLOWED_ORIGINS = [    'http://localhost:3030',] # If this is used, then not need to use `CORS_ALLOW_ALL_ORIGINS = True`CORS_ALLOWED_ORIGIN_REGEXES = [    'http://localhost:3030',]

more details: https://github.com/ottoyiu/django-cors-headers/#configuration

read the official documentation can resolve almost all problem


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)