Reputation: 274
I'm a bit confused as how to have a "Delete" button on a page that will delete the object currently in focus.
I'm trying to add this button to /edit/ to delete whichever id is open
Using Python3 and 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 delete function:
@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'))
Template (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 %}
So basically, I can load the edit/ page, but how do I hook up the "Delete" SubmitField to call the /delete/?
Upvotes: 2
Views: 4839
Reputation: 274
Figured it out. Posting answer for future folks. Not sure if best way, but only took 2 lines of code:
For the /edit/ route, I simply added this check.
if form.delete.data:
return redirect(url_for('servers.delete', id=id))
Which makes the entire edit route look like this:
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)
Upvotes: 5
Reputation: 4912
Maybe you can use customized validators. Like this:
delete = SubmitField('Delete', validators=delete())
About how to make a function a customized validator, check this link. The custom validators section.
Upvotes: 0