I have two forms on in my template: one, to post something and the second, to activate file deletion on the server:
<div style="margin-bottom:150px;">
<h4>Delete</h4>
<form method="post" action="/delete">
<div class="form-group">
<input type="hidden" name="delete_input"></input>
</div>
<button type="submit" class="btn btn-danger" id="btnSignUp">Delete</button>
</form>
</div>
<div style="margin-bottom:150px;">
<h4>URLs</h4>
<form method="post" action="/">
<div class="form-group">
<textarea class="form-control" rows="5" id="urls" name="url_area"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="btnSignUp">Urls</button>
</form>
</div>
My app.py
looks like this:
@app.route("/")
def main():
return render_template('index.html')
@app.route('/', methods=['POST'])
def parse_urls():
_urls = request.form['url_area'].split("\n")
image_list = get_images(_urls)
return render_template('index.html', images=image_list)
@app.route('/delete', methods=['POST'])
def delete_images():
file_list = [f for f in os.listdir("./static") if f.endswith(".png")]
for f in file_list:
os.remove("./static/" + f)
image_list = []
conn = sqlite3.connect('_db/database.db')
curs = conn.cursor()
sql = "DROP TABLE IF EXISTS images"
curs.execute(sql)
conn.commit()
conn.close()
return render_template('index.html', images=image_list)
Two issues:
The way I see it, I need so use redirects to avoid the duplicate submission and after calling delete, I need to redirect to index.
How can I do this correctly?
I know about redirect
and url_for
, but how do I redirect to the same page?
As archer said below:
return redirect(request.referrer)
This is useful when you have a button that uses a route to perform a given function when it is clicked - you don't want to return the user to the URL for that button - you want to return the user to the URL that the button route was referred by, i.e. the page the user was on when they clicked the button.
However, as Mahmoud said:
redirect(request.url)
This is perfect if you perform a function on a page that doesn't use routes or special URLs or anything like that. It essentially just refreshes the page.
You can get the currently requested URL by request.url
:
So, to redirect to the same page use:
redirect(request.url)
Change form action to action="{{url_for('delete_images')}}"
. And for redirection you can use code below:
@app.route('/delete', methods=['POST'])
def delete_images():
return redirect(url_for('delete_images'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With