Solutions to 403 errors in using jQuery Ajax post data in Django (two methods)

Time:2021-1-23

In Django, if you use jQuery Ajax post data, there will be 403 errors

Method 1

If you use jQuery to deal with Ajax, Django directly sent a piece of code to solve the problem. Put it in a separate JS file and import it in the HTML page. Note that this JS file must be imported after the JS file of jQuery is imported


$(document).ajaxSend(function(event, xhr, settings) { 
  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; 
  } 
  function sameOrigin(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)); 
  } 
  function safeMethod(method) { 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
  } 
  if (!safeMethod(settings.type) && sameOrigin(settings.url)) { 
    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); 
  } 
});

Method 2

Add @ CSRF before the view of post data_ Exempt decorator

for example


@csrf_exempt 
def profile_delte(request): 
  del_file=request.POST.get("delete_file",'')

The above two ways to solve the Django Ajax post 403 error, of course, the solution is more than these two, welcome to share their views, this article is not good, please forgive me, thank you.

Recommended Today

How to Build a Cybersecurity Career

Original text:How to Build a Cybersecurity Career How to build the cause of network security Normative guidelines for building a successful career in the field of information security fromDaniel miesslerstayinformation safetyCreated / updated: December 17, 2019 I’ve been doing itinformation safety(now many people call it network security) it’s been about 20 years, and I’ve spent […]