我想通過在我的djano應用程序中的Ajax後文件字段處理POST請求。 我得到這個錯誤:Ajax POST文件上傳在Django
Forbidden (CSRF token missing or incorrect.): /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('');
}
})
});
即使在console.log csrf_token字段中,它也會正確打印csrf標記。
有什麼問題嗎?
請幫幫我! 在此先感謝!
https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax – mindcruzer