2012-10-23 28 views
10

utilizzando django 1.4 im ottenere un errore 403 quando provo a fare un post dal mio javascript do my server django. il mio funziona bene anche se il problema riguarda solo il post. ha anche provato @csrf_exempt senza fortunadjango ajax post 403 vietato

AGGIORNAMENTO: Posso postare ora che ho aggiunto {% csrf_token %}, ma la risposta al post è vuota, anche se il GET viene correttamente, qualche idea?

mio punto di vista django:

@csrf_protect 
def edit_city(request,username): 
    conditions = dict() 

    #if request.is_ajax(): 
    if request.method == 'GET': 
     conditions = request.method 

    elif request.method == 'POST': 
     print "TIPO" , request.GET.get('type','')  
     #based on http://stackoverflow.com/a/3634778/977622  
     for filter_key, form_key in (('type', 'type'), ('city', 'city'), ('pois', 'pois'), ('poisdelete', 'poisdelete'), ('kmz', 'kmz'), ('kmzdelete', 'kmzdelete'), ('limits', 'limits'), ('limitsdelete', 'limitsdelete'), ('area_name', 'area_name'), ('action', 'action')): 
      value = request.GET.get(form_key, None) 
      if value: 
       conditions[filter_key] = value 
       print filter_key , conditions[filter_key] 

     #Test.objects.filter(**conditions) 
    city_json = json.dumps(conditions) 

    return HttpResponse(city_json, mimetype='application/json') 

Ecco il mio codice javascript:

function getCookie(name) { 
    var cookieValue = null; 
    if (document.cookie && document.cookie != '') { 
     var cookies = document.cookie.split(';'); 
     for (var i = 0; i < cookies.length; i++) { 
      var cookie = jQuery.trim(cookies[i]); 
      // Does this cookie string begin with the name we want? 
      if (cookie.substring(0, name.length + 1) == (name + '=')) { 
       cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
       break; 
      } 
     } 
    } 
    return cookieValue; 
} 
var csrftoken = getCookie('csrftoken'); 

function csrfSafeMethod(method) { 
    // these HTTP methods do not require CSRF protection 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
} 
function sameOrigin(url) { 
    // test that a given url is a same-origin URL 
    // url could be relative or scheme relative or absolute 
    var host = document.location.host; // host + port 
    var protocol = document.location.protocol; 
    var sr_origin = '//' + host; 
    var origin = protocol + sr_origin; 
    // Allow absolute or scheme relative URLs to same origin 
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || 
     (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || 
     // or any other URL that isn't scheme relative or absolute i.e relative. 
     !(/^(\/\/|http:|https:).*/.test(url)); 
} 
$.ajaxSetup({ 
beforeSend: function(xhr, settings) { 
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { 
     // Only send the token to relative URLs i.e. locally. 
     xhr.setRequestHeader("X-CSRFToken", 
          $('input[name="csrfmiddlewaretoken"]').val()); 
    } 
} 
}); 

$.post(url,{ type : type , city: cityStr, pois: poisStr, poisdelete: poisDeleteStr, kmz: kmzStr,kmzdelete : kmzDeleteStr,limits : limitsStr, area_nameStr : area_nameStr , limitsdelete : limitsDeleteStr},function(data,status){ 
        alert("Data: " + data + "\nStatus: " + status); 
        console.log("newdata" + data.area_name) 
       }); 

Ho provato anche dal sito senza fortuna:

$.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
     if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { 
      // Send the token to same-origin, relative URLs only. 
      // Send the token only if the method warrants CSRF protection 
      // Using the CSRFToken value acquired earlier 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
    } 
}); 

Che cosa mi manca ?

+1

Hai impostato DEBUG = True? Vai a Chrome Dev Tools -> Network e fai clic sulla tua richiesta non riuscita. Quale messaggio ricevi nella scheda Anteprima o Risposta? –

+0

ottengo una "verifica CSRF non riuscita. Richiesta interrotta". – psychok7

+0

stranamente ora la mia risposta post arriva VUOTA, qualche idea del perché? il funziona funziona ancora – psychok7

risposta

3

ottenuto che funziona con l'aggiunta di {% csrf_token %} da qualche parte all'interno del modulo nel mio modello

+0

csrf_token è un token anti-cross-site-request-forgery (http://en.wikipedia.org/wiki/Cross-site_request_forgery), ed è necessario perché 'django.middleware.csrf.CsrfViewMiddleware' è definito nella sezione MIDDLEWARE_CLASSES di settings.py. –

24

si può effettivamente passare questo insieme con i vostri dati {csrfmiddlewaretoken: '{{csrf_token}}'}, funziona tutto il tempo

+4

Il nome del token deve essere "csrfmiddlewaretoken", anziché "csrftoken". (Django 1.4) –

6

Nel mio caso ho un modello in cui non voglio avere un elemento <form></form>. Ma voglio ancora fare richieste AJAX POST usando jQuery.

Ho ricevuto 403 errori, poiché il cookie CSRF era nullo, anche se ho seguito i documenti django (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/). La soluzione è nella stessa pagina, menzionando il decoratore ensure_csrf_cookie.

mio biscotto CSRF fatto arrivare set quando ho aggiunto questo in cima alla mia views.py:

from django.views.decorators.csrf import ensure_csrf_cookie 
@ensure_csrf_cookie 

Inoltre, si ricorda che in questo caso si non è necessario l'elemento DOM nel markup/template : {% csrf_token %}

+0

Grazie! Ho dovuto usare quanto segue prima della mia definizione di classe poiché stavo usando le viste basate sulla classe: @method_decorator (ensure_csrf_cookie, name = 'update') – nbeuchat