I am trying to upload csv file from user and display it on the template. I have searched a lot for error but none has helped. So I decided to take help from this great community. Here is my code
views.py
@csrf_exempt
def offlineResults(request):
screenNametestList = []
friendsCountList = []
followersCountList = []
favouriteCountList = []
listedCountList = []
statusCountList = []
genEnabledList = []
protectedList = []
verifiedList = []
defaultProfileList = []
botsList = []
if request.method == 'POST' and request.FILES['filecsv']:
csv_file = request.FILES['filecsv']
data_set = csv_file.read().decode('UTF-8')
io_string = io.StringIO(data_set)
next(io_string) # skipping 1st line because 1st line contains header file
for column in csv.reader(io_string, delimiter=','):
screenNametest = column[0]
screenNametestList.append(screenNametest)
friends_countTest = column[1]
friendsCountList.append(friends_countTest)
followers_countTest = column[2]
followersCountList.append(followers_countTest)
favouriteCountTest = column[3]
favouriteCountList.append(favouriteCountTest)
listedCountTest = column[4]
listedCountList.append(listedCountTest)
statusCountTest = column[5]
statusCountList.append(statusCountTest)
geoEnabledTest = column[6]
genEnabledList.append(geoEnabledTest)
protectedTest = column[7]
protectedList.append(protectedTest)
verifiedTest = column[8]
verifiedList.append(verifiedTest)
defaultProfileTest = column[9]
defaultProfileList.append(defaultProfileTest)
botsTest = column[10]
botsList.append(botsTest)
dicCSV = {
'sc': screenNametestList,
'friendCount': friendsCountList,
'followersCount': followersCountList,
'favouriteCount': favouriteCountList,
'listedCount': listedCountList,
'statusCount': statusCountList,
'geoEnabled': genEnabledList,
'protected': protectedList,
'verified': verifiedList,
'defaultProfile': defaultProfileList,
'bots': botsList
}
return JsonResponse(dicCSV)
offline.html
<div class="container">
<h1 class="text-center"><b><u>Offline Results</u></b></h1>
<form class="md-form mt-4" method="post" enctype="multipart/form-data">
<div class="file-field">
<input type="file" name="filecsv" accept=".csv">
<button type="submit" id="load_csv" class="btn btn-default">Submit</button>
</div>
</form>
<div class="table-responsive mt-4">
<table class="table" id="data_table">
<thead>
<tr>
<th scope="col">ScreenName</th>
<th scope="col">FriendCount</th>
<th scope="col">FollowerCount</th>
<th scope="col">FavouriteCount</th>
<th scope="col">listedCount</th>
<th scope="col">statusCount</th>
<th scope="col">geoEnabled</th>
<th scope="col">Protected</th>
<th scope="col">Verified</th>
<th scope="col">DefaultProfile</th>
</tr>
</thead>
</table>
</div>
</div><!--end container-->
ajax part
$(document).ready(function () {
$('#load_csv').on('click',function (event) {
event.preventDefault();
$.ajax({
url: {% url 'offlineResults' %},
method: 'POST',
dataType:'json',
{#contentType: false,#}
{#cache: false,#}
{#processData: false,#}
success: function (jsonData)
{
$('#load_csv').val('');
$('#data_table').DataTable({
data : jsonData,
columns: [
{ data: 'sc'},
{ data: 'friendCount'},
{ data: 'followersCount'},
{ data: 'favouriteCount'},
{ data: 'listedCount'},
{ data: 'statusCount'},
{ data: 'geoEnabled'},
{ data: 'protected'},
{ data: 'verified'},
{ data: 'defaultProfile'}
]
});
}
})
});
});
It generates the following error
django.utils.datastructures.MultiValueDictKeyError: 'filecsv' [11/Apr/2019 20:41:48] "POST /offlineResults/ HTTP/1.1" 500 17525
What I am doing wrong. Help please
The entire traceback
Internal Server Error: /offlineResults/ Traceback (most recent call last): File "C:\Users\Mustajab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py", line 77, in getitem list_ = super().getitem(key) KeyError: 'filecsv'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Mustajab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Mustajab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Mustajab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mustajab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "F:\Final Year Project\FYPDjango\FYPapp\views.py", line 64, in offlineResults if request.method == 'POST' and request.FILES['filecsv']: File "C:\Users\Mustajab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py", line 79, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'filecsv' [11/Apr/2019 20:41:48] "POST /offlineResults/ HTTP/1.1" 500 17525
if ... and request.FILES['filecsv']
is failing. First you should userequest.FILES.get('filecsv')
because it might not be there. Second, you're not uploading the file in your ajax request. Search here on SO for how to upload a file with ajax. – dirkgroten