Django rest framework - Authentication error with PUT requests

前端 未结 3 704
迷失自我
迷失自我 2021-02-11 03:44

I have a very simple Resource like this for my model \'Presentacion\'

class PresentacionResource(ModelResource):
    m         


        
3条回答
  •  情书的邮戳
    2021-02-11 04:28

    I realize this is an older post, but I was dealing with this problem recently. Expanding on @orangewarp's answer and using django documentation (https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax), here's a solution:

    This solution uses the csrftoken cookie. Another solution would be to create a csrf token endpoint in your API and grab the csrf from there.

      Backbone._sync = Backbone.sync;
    
      Backbone.sync = function(method, model, options) {
          //from django docs
          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;
          }
    
          /* only need a token for non-get requests */
          if (method == 'create' || method == 'update' || method == 'delete') {
              var csrfToken = getCookie('csrftoken');
    
              options.beforeSend = function(xhr){
                  xhr.setRequestHeader('X-CSRFToken', csrfToken);
              };
          }
    
          return Backbone._sync(method, model, options);
      };
    

提交回复
热议问题