【问题标题】:How to handle errors in Django如何处理 Django 中的错误
【发布时间】:2020-01-19 12:54:04
【问题描述】:

我想让我的 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>

【问题讨论】:

  • 你有什么问题?您已经告诉我们您想要什么,但没有告诉我们当前代码存在什么问题。
  • request.FILES["excel_file"] 如果没有添加文件会抛出错误,你应该使用request.FILES.get("excel_file"),然后测试这是不是None,在这种情况下你会渲染你的页面并显示错误消息.我建议您阅读 this 并学习如何使用 Django 表单来验证输入并向用户显示任何错误。

标签: python html css django


【解决方案1】:

有两种方法:

  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 %}

【讨论】:

    【解决方案2】:

    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")然后您会在浏览器上看到 toast 消息。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-05
      • 2012-10-11
      • 2011-06-30
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多