我试图在我的djano应用程序中通过Ajax POST处理一个带有文件字段的POST请求。 我得到了这个错误:
Forbidden (CSRF token missing or incorrect.): /user/instance/create/new/awod/
我试过了:
来自模板.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
^{pr2}$即使我控制台.logcsrf_token字段,它正确打印csrf令牌。在
有什么不对劲吗?在
请帮帮我! 提前谢谢!在
使用
async:false
通常不是一个好主意,因为它会阻止页面上的其他事件触发您可能不希望您的代码暂停,我建议您像这样使用ajax:这也可以解决
csrf_token
的问题。在当您可以在数据中传递令牌时,recommended method将设置一个自定义的
X-CSRFToken
HTTP头:如您所见,该值是
csrftoken
cookie(由Django设置)。我用过jQuery.cookie库来检索令牌,但您可以根据需要检索它。在相关问题 更多 >
编程相关推荐