Skip to content

Instantly share code, notes, and snippets.

@baxeico
Last active August 6, 2020 13:40
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baxeico/fdec989a5e5ea0df0d0814edb4462b15 to your computer and use it in GitHub Desktop.
Save baxeico/fdec989a5e5ea0df0d0814edb4462b15 to your computer and use it in GitHub Desktop.
Simple mixin to add CORS headers in a Django View
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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment