提交表单时,我不希望重新加载页面,这就是为什么我使用ajax并将表单提交的数据获取到ajax的原因,而ajax会将请求发送到相应的view。但我无法在视图中找到文件上传控制的代码。我无法从以下位置获取数据:
myfile = request.FILES['myfile']
myfile =request.FILES['myfile'].read()
但是我总是出错:
如果request.method =='POST'并且request.FILES ['filename']提高 MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError:'文件名'
这是我的表格:
$(document).ready(function(evt){
$(document).on('submit','#myform',function(e){
e.preventDefault();
var thisForm=$(this).serialize();
var action=$(this).attr('action');
var method=$(this).attr('method');
var formData = new FormData($('#myform')[0]);
console.log(formData);
$.ajax({
url: action,
type: method,
data: formData,
success: function (data) {
alert(data)
},
cache: false,
enctype: 'multipart/form-data',
processData: false
});
});
});
<form action="{% url 'process_file' %}" method="post" enctype="multipart/form-data" id="myform">
{% csrf_token %}
<div class="col-md-3 col-sm-3 firstblock padMin">
<h3>Input Data</h3>
<ul>
<li><input type="file" name="files[]" required accept=".csv" id="file_data" ></li>
<li class="checkboxIn">
<input type="checkbox" name="id" id="id" />
</li>
<li>
<input type="number" name="train_fraction" id="train_fraction" required value={% if post_data %} {{fiction}} {% else %} 0.7 {% endif %} min="0.1" step="0.1" >
</li>
</ul>
</div>
<button class="btn btn-primary btn-lg custom-process" type="submit">Process</button>
and there are other control also
</form>
这是我在Python中的视图函数:
@csrf_exempt
def process_file(request):
#From submit action
if request.method == 'POST' and request.FILES['filename']:
print (request.POST)
id = '0' if request.POST.get('id',False)==False else '1'
res = '1' if 'res' in request.POST and request.POST['res']=='on' else '0'
ae_res = '1' if 'ae_res' in request.POST and request.POST['ae_res'] == 'on' else '0'
event_handling = '1' if 'event_handling' in request.POST and request.POST['event_handling'] == 'on' else '0'
threshold = request.POST['threshold'] if 'threshold' in request.POST else '1.0'
samplerate = request.POST['samplerate'] if 'samplerate' in request.POST else '0.1'
# myfile = request.FILES['myfile']
# myfile =request.FILES['myfile'].read()
#default action
return render(request, 'process_file.html',{})
如何在视图中读取文件控制数据,每当我在浏览器中打开控制台时,总会收到一条错误消息,指出500错误
答案 0 :(得分:0)
request.FILES['filename']
应该是request.FILES.getlist('files[]')
https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.QueryDict.getlist