Python & Flask HTML - 根据变量制作 n 个文本框

Python & Flask HTML - Making n number of textboxes based on variable

我有一个要创建的 Flask 网页。当用户注册一个帐户时,他们会声明他们拥有的农田数量。这保存在 MySQL 数据库中。由此,我需要用户在另一个输入页面上添加信息。此输入页面应具有“n”个文本框,具体取决于它们具有的字段数。

是否可以在 HTML 中创建“n”个文本框?我可以从他们的帐户中读取字段数,但找不到在 HTML 内创建可变数量文本框的方法。 我不需要它是动态的(用户添加或删除)这需要固定数量的文本框。

已找到解决方案,虽然有点难看,但应该可以。

在你的 html:

<table>
         {% for x in range(fields | int) %}
             <tr>
                    <td>
                <input type="text" value="{{ x }}">
                    </td>
                </tr>
            {% endfor %}
        </table>

在python中:

def irrigation_input():
   ...... non important stuff here.....
        fields=account_info_irr[9]
        int(float(fields))
            
        return render_template('irrigationinput.html',fields=fields)

我假设因为 flask 你使用 jina2 作为你的渲染引擎,让我们调用需要创建的字段数 n,你可以只使用循环结构

{% for i in range(n) %}
   <input name="field-{{i}}" />
{% endfor %}

您可以在 https://jinja.palletsprojects.com/en/3.0.x/templates/#for

获取更多信息

如果您需要更复杂的表格,我建议您使用 WTForms。