为什么我的django异常处理无法正常工作

时间:2019-09-18 13:36:33

标签: javascript python html css django

我想让我的django应用程序尽可能对用户友好,并且我想处理适当的异常处理案例,并使其发出类似JavaScript中警报的错误消息。当在这种情况下没有文件上传时,我想这样做“ POST” == request.method是空的。因此,当按下上载按钮并且没有上载任何内容时,将发出警报消息。但是到目前为止,我一直在执行的错误代码是:“视图uploadpage.views.upload没有返回HttpResponse对象。而是返回了None。”

def upload(request):

    try:
        if "Post" == request.method:
            excel_file = request.FILES["excel_file"]

        # you may put validations here to check extension or file size

            wb = openpyxl.load_workbook(excel_file)

        # getting a particular sheet by name out of many sheets
            worksheet = wb['Summary']

        # iterating over the rows and
        # getting value from each cell in row

            seller_info = []
            for cells in worksheet.iter_rows(min_col=2, max_col=2, min_row=1, max_row=5):
                for cell in cells:
                    seller_info.append(str(cell.value))
            return render(request, 'uploadpage/upload.html', {"excel_data": seller_info})
    except:
        if "POST" == None:
            messages.error(request, 'Need upload file')
            return render(request, 'uploadpage/upload.html')
<html>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="{% static 'css/upload.css' %}">
    <head>
        <div id='banner-container'>
        <div id='banner'>
            <h1 id='header'>MYAPP</h1> 
            <i class="glyphicon glyphicon-cloud" style="font-size:60px;color:lightblue;text-shadow:2px 2px 4px #000000;"></i>
        </div>
        <div>
        <body>
           <div>
               {% if messages %}
                <ul class='messages'>
                   {% for message in messages %} 
                   <div class='warningmessage'>
                       {{ message }}
                   </div>
                   {% endfor %}
                </ul>
               {% endif %}


           </div>
            <div id='upload-container' >
             <span><h1>Upload File !</h1></span>

             <span><h2>Upload Here</h2></span>

                <form method="post" enctype="multipart/form-data">
                    <div id='input'>
                            {% csrf_token %}
                        <input type="file" name="excel_file">
                        <div id='btn'><button type="submit">Upload File</button> </div>
                        </form>
                     <div>

            </div>
        </body>
        {{ excel_data }}
        <!-- {% for row in excel_data %}
            {% for cell in row %}
                {{ cell }}&nbsp;&nbsp;
            {% endfor %}
            <br>
        {% endfor %} -->
    </head>

</html>

1 个答案:

答案 0 :(得分:2)

if "POST" == None:

永远不会是真的。

请注意,您的代码还有很多其他问题。我建议您先进行 python 教程,然后再进行dj​​ango教程(两者都是完整的),并检查文档中的示例。

哦,是的:从不(我重复:从不)使用裸子句,从不(我重复:从不)假设您知道是什么引起异常。您当前的“异常处理程序”比没有用的要糟,这是有害的-它使您无法知道出了什么问题。