![](/img/trans.png)
[英]PYTHON WTForms flask - saving data from drop down list to database
[英]posting Flask wtforms in loop and saving data
我在for循環中有一個Flask-WTF表單字段。 我要為每個項目發布新數量。
我正在閱讀有關字段列表的信息。 我仍然不明白,但我認為它們可能是答案。
@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 %}
問題1:遍歷每個Flask-WTF表單字段時,其名稱相同。
輸出
<select id="quantity" name="quantity"><option value="1">1</option></select>
<select id="quantity" name="quantity"><option value="1">1</option></select>
問題2:如果每種表單的名稱不同,如何保存在支持的文件中。
我也有同樣的問題! 但是我沒有Flask-WTF來解決它,下面的解決方案基於我的應用程序。 我有一個相冊編輯頁面,我需要為相冊中每張圖片循環輸入文本,然后為每張圖片保存文本。
我以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">
然后,我循環圖片並保存輸入數據( 通過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.