Django @csrf_exempt decorator not working

I am using DJango 1.8 on a linode server and have the following look:

import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

def home_view(request):
        r = { 'response': 'OK', 'data': None }
        return HttpResponse(json.dumps(r), content_type = "application/json")

@csrf_exempt
def ping(request):
        r = { 'response': 'OK', 'data': 'ping' }
        return HttpResponse(json.dumps(r), content_type = "application/json")

      

My urls look like this:

urlpatterns = [
    url(r'^django/admin/', include(admin.site.urls)),
    url(r'^django/$', home_view),
    url(r'^django/ping/$', ping),
    url(r'^django/echo/$', echo),
]

      

If I go to my site http://mylinodesite/django/ping/

I get:

{"data": "ping", "response": "OK"}

Great. If i use jquery and do

$.get("http://mylinodesite/django/ping/")

I get

No 'Access-Control-Allow-Origin' header is present on the requested resource.

From what I understand, @csrf_exempt should get rid of the CSRF header stuff. What gives?

+3


source to share


2 answers


Daniel, it turns out you're partly right. It's CORS, but it can't be fixed on the jQuery side. Here is my Django view code that does what I want. Note that it adds a header Access-Control-Allow-Origin

to only allow requests from everyone ( *

) for only GET

.

This is also just a demonstration of how to do this in a single file. It is possible to create middleware to do this for all requests if needed, but this works and is a good example of how to do it all in one place so you can see what is going on and here is the full text of the entire view file :



def ping(request):
        r = { 'response': 'OK', 'data': 'ping' }
        response = HttpResponse("['ok']", content_type="application/json")
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'GET'

        return response

      

+2


source


This has nothing to do with CSRF, which is only for POST actions and is applied by Django.

You are performing a cross domain GET action. Browsers disallow this by default due to what is called a policy of the same origin: the JS script can only handle requests on the same domain it is loaded from. This way you are prevented by the browser itself.



To enable requests to named domains, you can use something called CORS , which uses a header in the request. See jQuery Ajax Documentation .

+2


source







All Articles