How can I enable CORS on Django REST Framework

0 votes
How can I enable CORS on my Django REST Framework?
Jul 1, 2020 in Python by kartik
• 37,490 points
882 views

1 answer to this question.

0 votes
Best answer

Hello @kartik,

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
)

Hope it works!!

Thank You!!

answered Jul 1, 2020 by Niroj
• 82,580 points

Related Questions In Python

0 votes
1 answer

How can modify request.data in django REST framework?

Hello @kartik, Generally request in drf views is rest_framework.request.Request instance. Following to ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,580 points
1,423 views
0 votes
1 answer

How can I enable project_id parameter of DJango to be optional?

Hello @kartik, There are several approaches. One is to ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,580 points
97 views
0 votes
1 answer

how to download and install Django rest framework?

To install Django, you can simply open ...READ MORE

answered Apr 24, 2018 in Python by Christine
• 15,830 points
632 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,580 points
618 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,580 points
256 views
0 votes
1 answer

How can I enable CORS on Django REST Framework?

Hello @kartik, Take the following steps to enable ...READ MORE

answered Jun 30, 2020 in Python by Niroj
• 82,580 points
1,927 views
0 votes
1 answer

How do I include related model fields using Django Rest Framework?

Hello @kartik, The simplest way is to use the ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,580 points
320 views