简体   繁体   English

在循环中发布Flask wtforms并保存数据

[英]posting Flask wtforms in loop and saving data

I have a Flask-WTF form fields in for loop. 我在for循环中有一个Flask-WTF表单字段。 I want to post the new quantities for each item. 我要为每个项目发布新数量。

I am reading about field list. 我正在阅读有关字段列表的信息。 I still dont understand but i think they might be the answer. 我仍然不明白,但我认为它们可能是答案。

@app.route('/checkout')
def checkout():
   form = CartForm()
    for item in current_user.cart:
        product = Product.query.get(item.product_id)
        cart_items.append({product: item.quantity})

    return render_template('checkout.html',cart_items=cart_items,form=form)



{% for item in cart_items %}
    {% for product, quantity in item.items() %}
        {{product.name}}
        {{product.price}}
        {{form.quantity }}
    {% endfor %}
{% endfor %}

Problem1: When looping over each Each Flask-WTF form field has the same name. 问题1:遍历每个Flask-WTF表单字段时,其名称相同。

The output 输出

<select id="quantity" name="quantity"><option value="1">1</option></select>
<select id="quantity" name="quantity"><option value="1">1</option></select>

problem2: how save in the backed if each form has a different name. 问题2:如果每种表单的名称不同,如何保存在支持的文件中。

I have the same problem exactly! 我也有同样的问题! But I solve it without Flask-WTF, the solution below was based on my app. 但是我没有Flask-WTF来解决它,下面的解决方案基于我的应用程序。 I have an album edit page, I need to loop a text input for each picture in album, then save the text for each picture. 我有一个相册编辑页面,我需要为相册中每张图片循环输入文本,然后为每张图片保存文本。

I loop the input in HTML, notice I set the action value for another view function and use each photo's id as each text input's name : 我以HTML形式循环输入,请注意,我为另一个视图函数设置了动作值,并使用每张照片的ID作为每个文本输入的名称

<form action="{{ url_for('edit_photo', id=album.id) }}" method="POST">
<ul>
    {% for photo in photos %}
    <li>
        <img class="img-responsive portrait" src="{{ photo.path }}" alt="Some description"/>
        <textarea name="{{ photo.id }}" placeholder="add some description" rows="3">{% if photo.description %}{{ photo.description }}{% endif %}</textarea>
    </li>
    {% endfor %}
</ul>
<hr>
<input class="btn btn-success" type="submit" name="submit" value="submit">

Then I loop the picture and save the input data ( get it's value by it's id ): 然后,我循环图片并保存输入数据( 通过id获得它的值 ):

@app.route('/edit-photo/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_photo(id):
    album = Album.query.get_or_404(id)
    photos = album.photos.order_by(Photo.order.asc())
    if request.method == 'POST':
        for photo in photos:
            photo.about = request.form[str(photo.id)]
            db.session.add(photo)
        return redirect(url_for('.album', id=id))
    return render_template('edit_photo.html', album=album, photos=photos)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM