首页 > 解决方案 > 使用 Flask 将值从 HTML 传递到 Python

问题描述

所以我使用 Flask 作为微框架,在我的一个模板中我使用下表:

<table id = "productentabel" width = "auto" class="table table-striped b-t b-b">
<thead>
<tr class = "header">
<th>Name</th>
<th>Url</th>
</thead>
{% for file in all_files['files'] %}
{% if file['mimeType'] == 'application/vnd.google-apps.document'  %}
<TR>
<TD  width="auto" >{{file['name']}}</TD> 
<td><a class="btn btn-xs white" href = "https://docs.google.com/document/d/{{file['id']}}" target ="_blank">Go to file</a></td>
<td><form method=POST action="delete_file"><input type=submit name="delete" value ="{{file['id']}}" class="btn btn-xs white">Delete file</input>
</form></td>
</TR>
{% endif %}
{% endfor %}
</tr> 
</table> 

我的问题是关于以下 HTML 代码:

<form method=POST action="delete_file"><input type=submit name="delete" value ="{{file['id']}}" class="btn btn-xs white">Delete file</input>
</form>

如您所见,当单击输入时,我试图将值传递给我的 Python 代码。该值被传递给我的 Python 代码,但现在该值在前端可见,所以它看起来像这样:

1svpTERHaYd-wSpFBRRRjp1TOj0H-FH4_66H2W1OLY 删除文件

但我希望它是这样的:

删除文件

在 Python 中,我正在执行以下操作来提取值:

fileid = request.form.get('delete')

我也尝试过这样的事情:

<form method=POST action="delete_file"><input type=submit name="{{file['id']" class="btn btn-xs white">Delete file</input>
    </form>

但是我真的不知道如何在我的 Python 代码中提取名称,因为我只需要file['id']被传递并且值解决方案对我有用,但这不是理想的解决方案。

标签: pythonhtmlflaskjinja2

解决方案


而不是POST尝试该GET方法,如下所示:

<td><form method="get" action="delete_file?file_name={{file['id']}}"><input type="submit" name="delete" value ="Delete file" class="btn btn-xs white"/></td>

如果你想要这个POST方法,你应该通过输入发送文件名和hidden类型。

<td><form method="post" action="delete_file"><input type="submit" name="delete" value ="Delete file" class="btn btn-xs white"/><input type="hidden" name="file_id" value="{{file['id']}}" /></td>

在这种情况下,您将获得如下文件 ID:

fileid = request.form.get('file_id')

顺便说一句:你的大部分 HTML 都是无效的,你真的应该看一个关于它的教程。


推荐阅读