【问题标题】:Ajax POST file upload in djangoDjango中的Ajax POST文件上传
【发布时间】:2017-08-03 03:43:17
【问题描述】:

我正在尝试通过我的 djano 应用程序中的 Ajax 帖子处理带有文件字段的 POST 请求。 我收到此错误:

禁止(CSRF 令牌丢失或不正确。):/user/instance/create/new/awod/

这是我尝试过的:

来自 template.html

<div class="container" style="background-color: lightgray; opacity: 0.7;margin-top:10%;margin-left: 2%; padding-bottom: 10%;">
          <form method="post" class="form-horizontal" action="" id="gitForm" enctype="multipart/form-data">
          {% csrf_token %}
          <div class="form-group">
          <label class="control-label" for="inputGroupSuccess1">Deployment Name:</label>
             <div class="input-group">
               <span class="input-group-addon">@</span>
               <input type="text" class="form-control" name="name" id="inputGroupSuccess1" aria-describedby="inputGroupSuccess1Status">
             </div>
          </div>
          <div class="form-group">
              <label class="control-label">Select File</label>
              <input type="file" id="inputGroupSuccess2" name="archive"  class="file" multiple   data-allowed-file-extensions='["zip", "tar"]'>
              <small id="fileHelp" class="form-text control-label" style="color:black">Upload a Tar or Zip archive without a Dockerfile, otherwise your deployment will fail.</small>
          </div>
          <div id="spinner" style="display: none;">
               <div class="f_circleG" id="frotateG_01"></div>
               <div class="f_circleG" id="frotateG_02"></div>
               <div class="f_circleG" id="frotateG_03"></div>
               <div class="f_circleG" id="frotateG_04"></div>
               <div class="f_circleG" id="frotateG_05"></div>
               <div class="f_circleG" id="frotateG_06"></div>
               <div class="f_circleG" id="frotateG_07"></div>
               <div class="f_circleG" id="frotateG_08"></div>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary btn-lg pull-right" value="Submit"> Submit </button>
                <span style="padding-right: 5%;float: right;"><a href="{% url 'users:new-instance' %}" class="btn btn-primary btn-lg"><img src="{% static 'images/go-back-arrow.svg' %}" style="width: 24px; height: 24px;"> Go Back! </a></span>
            </div>
          </form>
       </div>
      </div>
    </div>
</div>

我的 javascript

<script type="text/javascript">
$(document).ajaxStart(function() {
   $('#spinner').show();
   console.log("ajax start")
});

$(document).ajaxStop(function() {
   $('#spinner').hide();
});
$(document).on('submit', '#gitForm', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url : '/user/instance/create/new/awod/',
        data: {
            name:$('#inputGroupSuccess1').val(),
            archive:$('#inputGroupSuccess2').val(),
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
        },
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success:function () {
            $('#message').show();
            $('#inputGroupSuccess1').val('');
            $('#inputGroupSuccess2').val('');

        }
    })
});

即使我控制台记录 csrf_token 字段,它也会正确打印 csrf 令牌。

有什么问题吗?

请帮帮我! 提前致谢!

【问题讨论】:

标签: javascript jquery python ajax django


【解决方案1】:

虽然您可以在数据中传递令牌,但recommended method 是设置自定义X-CSRFToken HTTP 标头:

$.ajax({
    type: 'POST',
    headers: {'X-CSRFToken': $.cookie('csrftoken')},
    url : '/user/instance/create/new/awod/',
    data: {
        name:$('#inputGroupSuccess1').val(),
        archive:$('#inputGroupSuccess2').val()
    },
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success:function () {
        $('#message').show();
        $('#inputGroupSuccess1').val('');
        $('#inputGroupSuccess2').val('');
    }
})

如您所见,值为csrftoken cookie(由 Django 设置)。我已经使用 jQuery.cookie 库来检索令牌,但是您可以根据自己的喜好检索它。

【讨论】:

  • 正如我在帖子底部提到的,我使用 jQuery.cookie 库来检索令牌。您需要包含对库的引用,例如通过在 Django 模板中添加 &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"&gt;&lt;/script&gt;
【解决方案2】:

使用async:false 通常是个坏主意,因为它会阻止页面上的其他事件触发你可能不希望你的代码被暂停,我建议你像这样使用 ajax:

$(document).on('submit', '#gitForm', function (e) {
    var form_data = new FormData($(this)[0]);
    $.ajax({
        type:'POST',
        url:'/user/instance/create/new/awod/',
        processData: false,
        contentType: false,
        data : form_data,
        success: function(response) {
          $('#message').show();
          $('#inputGroupSuccess1').val('');
          $('#inputGroupSuccess2').val('');
        }
    });
});

这也应该可以解决您与csrf_token 相关的问题。

【讨论】:

  • 它在浏览器的控制台中返回[Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (awod, line 0)
  • @AbdulRehman 向我展示您的观点,您不应该使用 javascript 收到错误 500.. 一定是您认为的其他内容。
猜你喜欢
  • 2012-12-05
  • 2013-05-08
  • 1970-01-01
  • 2011-02-16
  • 1970-01-01
  • 2013-03-26
  • 2014-01-16
  • 2011-11-01
  • 1970-01-01
相关资源
最近更新 更多