【发布时间】:2020-01-19 11:43:15
【问题描述】:
我想让我的 django 应用程序尽可能地对用户友好,并且我想处理适当的异常处理情况并让它发出类似于 javascript 中的警报的错误消息。我想在这种情况下没有上传文件时执行此操作“POST”== request.method 是 emtpy。因此,当按下上传按钮并且没有上传任何内容时,会发出一条警报消息。但到目前为止,我一直在推送一条错误消息,上面写着“视图 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 }}
{% endfor %}
<br>
{% endfor %} -->
</head>
</html>
【问题讨论】:
-
只是一个小提示 - 您不应该捕获所有异常。尝试预测您期望的异常以及如何处理它们,而不是捕获各种异常,从找不到文件到连接超时到 json 解析错误。
-
你误会
try ... except。如果您想处理那里抛出的异常,它应该在您的第一个if条件内。但我不认为那是你的本意。只需if request.method == "POST": ... else: ...即可满足您的需求。 -
正如其他评论者所说,不要像那样使用
except。指定要捕获的异常。
标签: javascript python html css django