2

How can I stop Flask from re-adding form data to database on refresh?

My form.html sends data to approved.html like so:

if request.method == 'POST':
        element = db_name(request.form.get('element'))
        db.session.add(element)
        db.session.commit()
    else:
        return redirect(url_for('home'))
    return render_template('approved.html', current=element)

This so I can display the data from the form and let the user know entry has been added. But the problem is whenever I refresh approved.html which displays the form data, another copy of this entry is added to the database.

amars
  • 407
  • 6
  • 15

1 Answers1

4

This happens because the browser stores the state of the last request and refreshing will re-submit the form, leading to another entry in your database. This is also why it's normal practice to redirect on the server-side after successful form submission. See Preventing POST on reloading a form and here

What you need to do is to successfully handle a successful form request and then redirect the user to a fresh state.

So something like this

return redirect(url_for('success'))

can be added instead of the render_template function which will then be redirected to the assigned function; there you can call the render_template of your choice.

AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35
  • Thank you. That makes a lot of sense. Would you know how is it that I can fetch the ID that was auto generated when the entry was added? This so I can display a - added successfully - message. – amars Jul 03 '20 at 12:02
  • Is [this](https://stackoverflow.com/questions/6242756/how-to-retrieve-inserted-id-after-inserting-row-in-sqlite-using-python) what you are looking for? You can also use that method to fetch the last record before the entry is made and then once the new entry is inserted; check if they are same or different. In the latter case you can simply display that value – AzyCrw4282 Jul 03 '20 at 15:00