如何处理Django中的错误

时间:2019-09-18 14:16:07

标签: python html css django

我想让我的django应用程序尽可能对用户友好,我想处理适当的错误,并使其发出类似JavaScript中警报的错误消息。没有文件上传时,我想这样做。因此,当按下上载按钮并且没有上载任何内容时,将发出警报消息。

我的观点,views.py

def upload(request):

    if "GET" == request.method:
        return render(request, 'uploadpage/upload.html', {})

    else:
        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})

我的模板uploadpage/upload.html

  <!DOCTYPE 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'>MY APP</h1> 
            <i class="glyphicon glyphicon-cloud" style="font-size:60px;color:lightblue;text-shadow:2px 2px 4px #000000;"></i>
        </div>
        <div>
        <body>
            <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 }}
    </head>

</html>

2 个答案:

答案 0 :(得分:3)

Django为我们提供了a message framework,允许您附加消息,然后可以使用JavaScript或仅使用django模板将其呈现在模板上。

我最喜欢的在Web应用程序上显示消息的库是toastr。您可以转到文档页面,查看如何将其集成到项目中。

您的看法:

from django.contrib import messages

# ...

def upload(request):

if "GET" == request.method:
    messages.error(request, "There's no file uploaded")
    return render(request, 'uploadpage/upload.html', {})

# ...

然后在模板上可以像这样使用它:

...
<head>
    ...
    <link href="toastr.min.css" rel="stylesheet" />
</head>
<body>
    ...

    <script src="toastr.min.js"></script>
    {% if messages %}
        <script>
            toastr.options = {
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "5000"
            }
            {% for message in messages %}
                toastr.{{ message.tags }}("{{ message }}");
            {% endfor %}
        </script>
    {% endif %}
</body>
  • message.tags:用于与Toastr的功能匹配,例如,如果您想通过使用messages.error(...)来显示错误,则message.tags将是error,当您的模板将其渲染为toastr.error("Your message here"),然后您将在浏览器中看到烤面包消息。

希望有帮助!

答案 1 :(得分:0)

有两种解决方法:

  1. 您可以创建客户端检查,以防止使用Javascript发送表单。那不是特定于Django的,并且您可以轻松找到示例。

  2. 您发现没有文件发送的事实,并为upload.html模板设置了额外的标志。未经测试的示例代码:

    message = None
    data = None
    if request.FILES:
        data = # process file
        message = "Upload successful!"
    else:
        message = "Please upload a file!"
    return render(request, 'upload.html', {"data": data, "message": message})

然后,您可以在模板中显示message

{% if message %}
    <div class="message">{{message}}</div>
{% endif %}