gpt4 book ai didi

javascript - 为什么我的 Django 异常处理不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:39 24 4
gpt4 key购买 nike

我想让我的 Django 应用程序尽可能对用户友好,我想处理适当的异常处理情况,并让它推出类似于 javascript 中的警报的错误消息。我想在没有文件上传时执行此操作,在这种情况下“POST”== request.method 是空的。因此,当按下上传按钮且未上传任何内容时,将发出一条警告消息。但到目前为止,我的代码一直在推出一条错误消息,上面写着“ View 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 }}&nbsp;&nbsp;
{% endfor %}
<br>
{% endfor %} -->
</head>

</html>

最佳答案

这个

if "POST" == None:

永远不会是真的。

请注意,您的代码还有很多其他问题。我诚挚地建议您先学习 python 教程,然后再学习 django 教程(两者都是完整的),并查看文档中的示例。

哦,是的:NEVER(我重复:NEVER)使用纯 except 子句,并且 NEVER(我重复:NEVER)假定您知道导致异常的原因。您当前的“异常处理程序”比无用更糟糕,它是有害的 - 它使您无法知道出了什么问题。

关于javascript - 为什么我的 Django 异常处理不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57994076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com