我尝试从<input type="file" id="file" name="file" accept="image/*" multiple>
发送图像而不发送任何表格。我发现很多帖子对此做了解释,所以我这样做
urls.py
url(r'^images/', 'app.views.images', name='images'),
view.py
def images(request):
if request.method == 'POST':
print('hello')
jquery
$("#file").change(function (){
try{
var formdata = new FormData();
var files = $('#file')[0].files;
formdata.append('file',files);
jQuery.ajax({
url: "images/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
}
catch(err){
alert(err.message);
}
});
但这给了我"POST /images/ HTTP/1.1" 403
错误
我做了不同的测试,我认为错误是data: formdata
部分
答案 0 :(得分:1)
您需要在ajax请求中发送csrf_token
。
formdata["csrfmiddlewaretoken"] = '{{ csrf_token }}'; //add csrf token to the reauest data
jQuery.ajax({
url: "images/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
或在您的视图上使用@csrf_exempt。
#views.py
@csrf_exempt
def images(request):
if request.method == 'POST':
print('hello')