gpt4 book ai didi

Python Flask - 如何使用 SubmitField 删除对象?

转载 作者:行者123 更新时间:2023-12-01 04:48:36 25 4
gpt4 key购买 nike

我对如何在页面上添加“删除”按钮来删除当前焦点对象感到有点困惑。

我正在尝试将此按钮添加到/edit/以删除打开的 id

使用Python3和Flask

表单.py

class EditForm(Form):
name = StringField('Server Name', validators = [Length(1, 120), DataRequired()])
ip_address = StringField('IP Address', validators = [Length(1, 16), IPAddress()])
username = StringField('UCX User', validators = [Length(1, 64)])
password = StringField('UCX Password', validators = [Length(1, 64)])
description = StringField('Purpose/Description', validators = [Length(1-120)])
protocol = RadioField('Protocol', [DataRequired()],
choices=[('https', 'HTTPS'), ('http', 'HTTP')], default='https')

submit = SubmitField('Submit')
**delete = SubmitField('Delete')**

路线.py

@servers.route('/edit/<id>', methods=['GET', 'POST'])    
def edit(id):
server = UcxServer.query.filter_by(id=int(id)).first_or_404()
form = EditForm(obj=server)
if form.validate_on_submit():
form.to_model(server)
db.session.commit()
flash('Your changes have been saved.')

return render_template('addserver2.html', form=form)

Routes.py删除函数:

@servers.route('/delete/<id>')
def delete(id):

server = UcxServer.query.filter_by(id=int(id)).first_or_404()
try:
db.session.delete(server)
db.session.commit()
flash('Successfully deleted the {} server'.format(server))
return redirect(url_for('servers.index'))

模板(addserver2.html):

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block page_content %}
<div class="page-header">
<h1>UCX Server</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}

所以基本上,我可以加载编辑/页面,但是如何连接“删除”SubmitField 来调用/delete/?

最佳答案

想通了。为 future 的人们发布答案。不确定是否是最好的方法,但只用了两行代码:

对于/edit/路线,我只是添加了此检查。

if form.delete.data:

return redirect(url_for('servers.delete', id=id))

这使得整个编辑路线如下所示:

def edit(id):
server = UcxServer.query.filter_by(id=int(id)).first_or_404()
form = EditForm(obj=server)
if form.delete.data:

return redirect(url_for('servers.delete', id=id))

if form.validate_on_submit():
form.to_model(server)
db.session.commit()
flash('Your changes have been saved.')

return render_template('addserver2.html', form=form)

关于Python Flask - 如何使用 SubmitField 删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com