Django view with cross-domain Ajax

ajax, django

Solution

Try add this middleware.

How to add see documentation https://docs.djangoproject.com/en/dev/topics/http/middleware/

Problem

I have a Django view that I want to integrate with an Ajax call. The call is happening cross domain. I have this code running by itself and making the request cross-domain. ``` def myview(_request): response = HttpResponse(json.dumps({"key": "value", "key2": "value"})) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" return response ``` I am wondering how to integrate this into my existing view. You will see what I have tried in the code below: ``` def american_time(request): #Calling the HTML Source from the URL sock = urllib.urlopen("http://apps.cbp.gov/bwt/index.asp") htmlSource = sock.read() sock.close() #create a soup object soup = BeautifulSoup(htmlSource) #find the tags we need and their content bridge = soup.findAll('td', limit=215)[194] tunnel = soup.findAll('td', limit=250)[208] #new variables to be passed contents_of_tunnel = tunnel.getText(', ') contents_of_bridge = bridge.getText(', ') #check to see if there is a delay for the bridge if 'no delay' in contents_of_bridge: time_to_cross_the_bridge = 0 else: inside_of_bridge = re.split(r', ', contents_of_bridge) number_inside_of_bridge = inside_of_bridge[1] list_for_time_to_cross_the_bridge = re.findall(r"\d+", number_inside_of_bridge) time_to_cross_the_bridge = list_for_time_to_cross_the_bridge[0] if 'no delay' in contents_of_tunnel: time_to_cross_the_tunnel = 0 else: inside_of_tunnel = re.split(r', ', contents_of_tunnel) number_inside_of_tunnel = inside_of_tunnel[1] list_for_time_to_cross_the_tunnel = re.findall(r"\d+", number_inside_of_tunnel) time_to_cross_the_tunnel = list_for_time_to_cross_the_tunnel[0] response = HttpResponse(json.dumps({"bridge_time": time_to_cross_the_bridge, "tunnel_time": time_to_cross_the_tunnel})) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" #finally, return as Ajax return HttpResponse(response) ``` AJAX: ``` $.get( "http://localhost:8000/us", function(json){ $('#timeone').html(json.bridge_time + "min delay"); $('#timetwo').html(json.tunnel_time + "min delay"); }) .fail(function(){ alert('We can\'t get data right now! Please try again later.'); }) .done(function(){ alert('Success!'); }); ``` However, I am still getting the message `XMLHttpRequest cannot load http://localhost:8000/us. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.` in the console. How can I integrate this header into my view?

Original source