This artice describes how to enable CORS in a Django response by adding a header to the HttpResponse.

Access to XMLHttpRequest has been blocked by CORS policy in Django response.

When a Django get method returns an HttpResponse, it does not include a header to enable CORS. This results in this error in the browser console:

Access to XMLHttpRequest at 'xyz' from origin 'zyx' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

Enable CORS in Django

Create an HttpResponse but before returning it, add an 'Access-Control-Allow-Origin' header like this:

from django.http import HttpResponse
from django.views.generic import TemplateView


class TestView(TemplateView):
    def get(self, request):
        response = HttpResponse("hello!")
        response.headers["Access-Control-Allow-Origin"] = "*"
        return response

As an alternative you can pip install 'django-cors-headers' and configure CORS via setup.py but if you are looking for a lightweight solution, the code above might do the trick for you. Of course you need to be careful what domains you allow to use CORS. Use this at your own risk.

Written by Loek van den Ouweland on 2022-07-23.
Questions regarding this artice? You can send them to the address below.