[英]how to put data(id) in form (wtforms) and get it back on submit
我是wtforms的新手,所以我將非常感謝您的幫助。
我需要顯示書籍名稱,並在每個放置“刪除”按鈕的位置附近顯示。 我讀過wtforms崩潰課程,但是我不知道如何解決它的問題。
因此,我決定以其他方式進行操作-我最好的主意是將具有ID和名稱的dict渲染為模板,並在提交返回ID時將其渲染為模板,但是我還是做不到。 代碼示例如下。
它的view.py
@application.route('/delete', methods=['GET', 'POST'])
def delete():
books_lib = mydatabase.get_all_books()
form = DeleteForm(request.form)
if request.method == 'POST':
delete_id = form.id.data
mydatabase.del_book(delete_id)
return render_template('delete.html', form = form, books_lib = books_lib)
return render_template('delete.html', form = form, books_lib = books_lib)
它的模板
<!DOCTYPE html>
<html>
<body>
<h2>book to delete</h2>
<form action="/delete" name="delete" method="POST">
{% if books_lib %}
{% for id, book in books_lib.items() %}
<p>{{book}}:<input type="submit" value="Delete" id="{{id}}">
{% endfor%}
{% endif %}
</form>
</body>
</html>
它的形式
class DeleteForm(Form):
book = TextField("Book name", [validators.Length(min=2, max=25)])
id = HiddenField("id")
這是我的方法。
模板
<p><a href="{{ url_for('delete_post', url=post.url) }}">delete</a></p>
視圖
# delete a post
@app.route('/<path:url>/d')
@login_required
def delete_post(url):
post = Post.get_post(url)
if post is None:
flash('post not found')
return redirect(url_for('home'))
db.session.delete(post)
db.session.commit()
Topic.update_counts()
flash('Your post has been deleted')
return redirect(url_for('index'))
url_for是一個Flask函數,它生成一個url並將其綁定到一個函數。
太...簡而言之。
回答您的原始問題。
如果您只想將ID列表傳遞給模板...。
首先,創建顯示功能。
@app.route('/index')
def index():
posts = Post.query.order_by(Post.pub_date.desc()) #SQLAlchemy query.
return render_template('index.html', posts=posts) #sends all posts to template.
現在,您可以在模板中生成post.id列表。
{% for post in posts %}
{{post.id})
{% endfor %}
要在列表中的每個項目旁邊添加刪除鏈接,請使用url_for。
{% for post in posts %}
<p>{{post.id}) <a href="{{ url_for('delete_post', id=post.id) }}">delete</a></p>
{% endfor %}
在這種情況下,我使用post id而不是post.url來標識要刪除的特定帖子,因此不要忘記在delete函數中修改@ app.route。
@app.route('/<int:id>/delete')
請注意,此解決方案不需要表格。 僅當您想要使用復選框進行批量刪除時,才需要一個表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.