【问题标题】:Flask Form Only Passing First Item烧瓶形式仅通过第一项
【发布时间】:2017-08-03 11:58:06
【问题描述】:

出于学习目的,我正在使用 Flask 构建一个购物车。我选择将 SQLite 与 peewee(ORM) 和 WTForms 一起使用。我将其设置为显示来自数据库的项目以及描述和图像。我有一个要求数量的表格,然后它应该将项目及其数量添加到侧栏。

问题

当您输入一个数量并点击“添加”时,所有数量字段都将填充该数字,并且它将以该数量将数据库中第一个项目的名称发布到侧边栏。

app.py

@app.route('/cart', methods=['GET', 'POST'])
@login_required
def cart():
    form = forms.PartsSelectForm()
    if request.method == 'POST':
        l_name = Parts.get(Parts.id).part_name
        models.List.create(l_part_name=l_name,
                           l_part_qty=form.quantity.data)
    parts = Parts.select()
    list = List.select()
    return render_template('cart.html', parts=parts, list=list, form=form)

forms.py

class PartsSelectForm(Form):
    quantity = IntegerField()

cart.html

<table class="table">
            <thead>
            <tr>
            <th>Name</th>
            <th>Description</th>
            <th>Image</th>
            <th>Quantity</th>
            <th>Action</th>
            </tr>
            </thead>

            {% for part in parts %}
            <tr>
                <td>{{ part.part_name }}</td>
                <td>{{ part.part_desc }}</td>
                <td style="width: 200px; height:200px;"><img src="/static/img/{{ part.part_img }}" style="max-height:100%; max-width:100%"></td>
                <form method="POST" action="">
                    <td>{{ form.quantity }}</td>

                <td><button type="submit" id="submit" class="btn btn-success">Add</button></td>
</form>
            </tr>
            {% endfor %}
        </table>

【问题讨论】:

    标签: python flask flask-wtforms flask-peewee


    【解决方案1】:

    你循环你的部分,但你总是使用 form.quantity,它在每次迭代中都是相同的,这与你当前循环的“部分”无关。

    【讨论】:

    • 但是,如果我不将每个项目数量包含在循环中,我将如何拥有一个字段?
    猜你喜欢
    • 2018-01-07
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多