How can I enable CORS on my Django REST Framework? the reference doesn't help much, it says that I can do by a middleware, but how can I do that?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
Below are the working steps without the need for any external modules:
Step 1: Create a module in your app.
E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.
Lets call this as custom_cors_middleware.py
Paste the below Class definition:
Step 2: Register a middleware
In your projects settings.py file, add this line
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'
E.g:
Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.
You can now verify it will add the required response headers to all the views in the project!
After installing
django-cors-headers
and adding it to your middlewares, you may also need to migrate in order for the CorsModel model to be created in your DB. I was getting exceptions while trying to flush it otherwise.