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

时间:2015-03-06 01:24:19

标签: python flask wtforms

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

我正在尝试将此按钮添加到/编辑/删除任何ID已打开

使用Python3和Flask

forms.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')**

Routes.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 /?

2 个答案:

答案 0 :(得分:2)

想出来。为未来的人们发布答案。 不确定是否最好的方法,但只花了2行代码:

对于/ edit / route,我只是添加了这个检查。

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)

答案 1 :(得分:0)

也许你可以使用自定义验证器。像这样:

delete = SubmitField('Delete', validators=delete())

关于如何使功能成为自定义验证器,请检查此link。自定义验证器部分。