Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-Control-Allow-Origin in Django app

I'm developing a Phonegap app for my Django based app, but when trying to make Ajax calls I get this error:

XMLHttpRequest cannot load http://domain.herokuapp.com/getcsrf/?tags=jquery%2Cjavascript&tagmode=any&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.  

How can I make it so my Django app allows cross origin for some urls?

Here's my Ajax code:

get: function() {     $.getJSON("http://domain.herokuapp.com/getcsrf/",     {         tags: "jquery,javascript",         tagmode: "any",         format: "json"     },     function(data) {         $.each(data.items, function(item){             console.log(item);             });     }); } 
like image 585
Sascuash Avatar asked Mar 12 '14 15:03

Sascuash


People also ask

What are CORS in Django?

Django is a Python web framework that allows rapid web application development. Apps developed in Django may need to interact with other applications hosted on different domains (or even just different ports). For these requests to succeed, you'll need to use cross-origin resource sharing (CORS) in your server.


2 Answers

Django by default does not provide the headers necessary to provide cross origin. The easiest way would be to just use this Django app that handles it for you: https://github.com/adamchainz/django-cors-headers

  • Add to installed apps
  • Add to middleware
  • Then stuff like...
CORS_ALLOWED_ORIGINS = [     "http://read.only.com",     "http://change.allowed.com", ] 

to support allowing all, just use the setting... CORS_ALLOW_ALL_ORIGINS = True and then do any filtering of the request in middleware or in the view.

like image 152
stormlifter Avatar answered Oct 21 '22 00:10

stormlifter


For single views you can manually add headers:

@require_GET def api_getto(request):     response = JsonResponse(         # your stuff here     )     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"     return response 
like image 25
mariusz_latarnik01 Avatar answered Oct 20 '22 22:10

mariusz_latarnik01