MultiValueKeyDictError Django在上传csv文件时

时间:2019-04-11 15:55:01

标签: django

我正在尝试从用户上传csv文件,并将其显示在模板上。我已经搜索了很多错误,但是没有帮助。因此,我决定从这个伟大的社区中寻求帮助。这是我的代码

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部分

$(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'}

                        ]
                    });
                }
            })
        });

    });

它会产生以下错误

  

django.utils.datastructures.MultiValueDictKeyError:'filecsv'       [11 / Apr / 2019 20:41:48]“ POST / offlineResults / HTTP / 1.1” 500 17525

我做错了。请帮助

整个追溯

  

内部服务器错误:/ offlineResults /追溯(最近的呼叫   最后):文件   “ C:\ Users \ Mustajab \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ django \ utils \ datastructures.py”,   第77行,在 getitem       list_ = super()。 getitem (密钥)KeyError:'filecsv'

     

在处理上述异常期间,发生了另一个异常:

     

回溯(最近通话最近):文件   “ C:\ Users \ Mustajab \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ django \ core \ handlers \ exception.py”,   第34行,在内部       response = get_response(request)File“ C:\ Users \ Mustajab \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ django \ core \ handlers \ base.py”,   _get_response中的第126行       响应= self.process_exception_by_middleware(e,request)文件“ C:\ Users \ Mustajab \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ django \ core \ handlers \ base.py”,   _get_response中的第124行       响应= wraped_callback(请求,* callback_args,** callback_kwargs)文件“ C:\ Users \ Mustajab \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ django \ views \ decorators \ csrf.py” ,   第54行,在wrapped_view中       在离线结果中返回view_func(* args,** kwargs)文件“ F:\ Final Year Project \ FYPDjango \ FYPapp \ views.py”,第64行       如果request.method =='POST'和request.FILES ['filecsv']:文件“ C:\ Users \ Mustajab \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ django \ utils \ datastructures.py”,   第79行,在 getitem       引发MultiValueDictKeyError(key)django.utils.datastructures.MultiValueDictKeyError:'filecsv'   [11 / Apr / 2019 20:41:48]“ POST / offlineResults / HTTP / 1.1” 500 17525

1 个答案:

答案 0 :(得分:0)

该错误是因为您正在访问词典中不存在的键。当您检查字典中的值是否存在时,就像您在if request.FILES[‘filecsv’]中所做的那样,应该使用get()而不是下标([])来避免KeyError 。所以:

if request.FILES.get('filecsv')

更改后,您会发现if条件为False,并且会收到另一个错误,因为在这种情况下视图不返回任何内容。始终返回HttpResponse。可能是同一页面,并在此处显示错误消息。

现在的主要问题是您的Ajax调用未提交任何数据。它只是执行POST请求而没有任何数据。检查here如何使用jquery ajax上传文件。