'How to keep the information a user entered in a form after submitting it if the user made an error in flask?

I created a sign up form using html and jinja that sends a post request when it is submitted

  <form method="POST">
    <div class="mb-3 text-center">
      <label for="email" class="form-label"
        >Email Address:
      </label>
      <input
        type="email"
        class="form-control"
        id="email"
        name="email"
        placeholder="Enter email"
      />
    </div>

with other inputs and a button which submits it all at the bottom of the form

My auth.py file which holds the routes for the forms has this function which checks if the information the user entered is valid. If it isn't send an alert flash message, and if it is create the user.

@auth.route("sign-up", methods=["GET", "POST"])
def sign_up():
    if request.method == "POST":
        email = request.form.get("email")
        if len(email) < 4:
            flash("Email must be greater than 4 characters!", category="dangerAlert")
        else:
            flash("You have successfully created an account!", category="successAlert")

All of this works however, when the user enters invalid informaiton, all of input fields lose the text they wrote. So the user has to rewrite all the text in the input fields to resubmit their form. How do I keep the text in the input fields if the user sends invalid or incomplete data?



Solution 1:[1]

The best way to do this that I know of, and have used in the past: is using localStorage. You set the local storage before they reload the page. Like this:

function setLocalStorage {
  localStorage.setItem("name", $('#text').val());
  localStorage.setItem("email", $('#email').val());
}
window.onbeforeunload = function() { setLocalStorage(); }

Forgive my js, I haven't done any web dev in a little while. Obvously, you would also need to reload this onload()

Idea: jcubic

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dat Boi