【发布时间】: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 表单来验证输入并向用户显示任何错误。