When I submit the form I don't want page to be reload that's why I use ajax and get data on form submission to ajax and ajax will send request to corresponding view . but I am unable to find code for file upload control in view. I am unable to get data from:
myfile = request.FILES['myfile']
myfile =request.FILES['myfile'].read()
but i am always getting error :
if request.method == 'POST' and request.FILES['filename'] raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'filename'
this is my form :
$(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>
Here is my view function in 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',{})
how to read file control data in view and I am always getting an error saying 500 error whenever I open a console in the browser