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,520 points
2,005 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,840 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 2, 2020 in Python by Niroj
• 82,840 points
5,434 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,840 points
913 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,790 points
1,959 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,840 points
2,437 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,840 points
1,555 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,840 points
4,241 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,840 points
3,628 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP