我想让我的 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>
Django 为我们提供了消息框架 https://docs.djangoproject.com/en/2.2/ref/contrib/messages/它允许您附加消息,然后您可以使用以下命令将其呈现在模板上JavaScript
或者只是使用 django 模板。
我最喜欢在网络应用程序上显示消息的库是toastr https://github.com/CodeSeven/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 消息。
希望有帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)