How to add CORS headers to a Django view for use with a Cordova app


Fri 27 May 2016

Suppose you want to access some JSON data from a mobile app using Cordova. You have to bypass CORS restrictions in the web view, and to do that you have to provide some HTTP headers in your Django views.

You can do this pretty easily by using this mixin in your Class Based Views:

from django.http import HttpResponse

class AllowCORSMixin(object):

    def add_access_control_headers(self, response):
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
        response["Access-Control-Max-Age"] = "1000"
        response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type"

    def options(self, request, *args, **kwargs):
        response = HttpResponse()
        self.add_access_control_headers(response)
        return response

Use it like in the example below. Here used together with Django Braces app:

from django.views.generic import View

from braces.views import AjaxResponseMixin, JSONResponseMixin

class JsonView(JSONResponseMixin, AjaxResponseMixin, AllowCORSMixin, View):

    def get_ajax(self, request, *args, **kwargs):

        # ... get some data ...

        response = self.render_json_response({ 'data': data })
        self.add_access_control_headers(response)
        return response

Share: