使用ajax和djangorestframework 403错误通过django表单发送文件

时间:2017-04-03 17:59:32

标签: jquery python ajax django django-rest-framework

我正在尝试使用ajax从django模板表单发送pdf文件,并使用djangorestframwork在views.py中获取数据。使用常规数据,但在这种情况下,我得到403错误

forms.py

class TicketForm(forms.ModelForm):
    class Meta:
        model = Ticket
        fields = ('upload',)
        widgets = {
            'upload': forms.FileInput(
                attrs={'id': 'fileinput', 'required': True, 'placeholder': 'Say something...'}
            ),
        }

模板和jQuery / js:

 <form method="post" enctype="multipart/form-data" class="pdf_form">
{% csrf_token %}
            {{ form.as_p }}


      <input type="submit" class="">Save</input>
  </form>




 <script type="text/javascript">

 $(function() {

function upload() {
   alert($('#fileinput').val())

   $.ajax({
        url: '/upload_ticket/',
        type : "POST", // http method
        dataType: 'json',
        data : { 'file' : $('#fileinput').val() }, // data sent with the post request

        // handle a successful response
        success : function() {
          alert('succes');
        },

        // handle a non-successful response
        error : function() {
           alert('error');
        }
    });
};






    $('.pdf_form').on('submit', function(e){
    e.preventDefault();
    alert('it works!');
    console.log("form submitted!")  // sanity check
    upload();
});



});

</script>

urls.py:

    url(r'^upload_ticket/$', views.upload_ticket),

views.py:

@api_view(['POST', ])
def upload_ticket(request):
    return Response(request.data)

我已调试好几个小时,但无法发现错误。我的实施有什么问题?

POST /upload_ticket/ HTTP/1.1" 403 58

3 个答案:

答案 0 :(得分:1)

您没有在API调用中发送csrf令牌,这就是罪魁祸首。 这应该适合你。

  $.ajax({
    url: '/upload_ticket/',
    type : "POST", // http method
    dataType: 'json',
    data : { 'file' : $('#fileinput').val(), 'csrfmiddlewaretoken' : document.getElementsByName('csrfmiddlewaretoken')[0].value }, // data sent with the post request

    // handle a successful response
    success : function() {
      alert('succes');
    },

    // handle a non-successful response
    error : function() {
       alert('error');
    }
});

};     

答案 1 :(得分:0)

403错误发生是因为您没有在请求中发送csrf令牌,

您必须将csrf令牌设置为您的请求标头,您可以使用此code以及js文件或js块的末尾,所有这些都应该没问题。

另外我想向您推荐这个关于django /和ajax的post,对我来说非常有用

答案 2 :(得分:0)

 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));
}

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

在jQuery库之后添加,它总是将csrftoken传递给你的请求,你不需要再手动传递csrftoken了!