简体   繁体   中英

auto-saving the contents of a WTForm

I am making a (quite frankly) somewhat tenuous form. As such, I want it to save every time they input something into a data field. However, I don't want to save them as a user to the site until the form is complete and validated.

This is what I imagine the javascript side to contain

$('input').blur(function() {
  $.post(endpoint, form);
});

however, what I currently have for the endpoint is something like this:

@auth.route('/register', methods=['GET', 'POST'])
def register():
    """ register a new user using the form """
    form = RegistrationForm()
    if form.validate_on_submit():
        new_user = User(
            email=form.email.data.lower(),
            first_name=form.first_name.data.title(),
            last_name=form.last_name.data.title(),
            username=form.username.data.lower(),
            password=form.password.data
        )
        db.session.add(new_user)
        flash('successfully registered!', 'success')
        return redirect(url_for('auth.login'))
    return render_template('user/register.html', form=form)

this works well to register a user, but how do I simply save their form data for later use if they revisit without making them a user?

I think you have to store each session into database, you have to load the partial filled form data when the session and cookie communicates.

IMHO, when the new user comes to the application new session will be created, you have to store that session into database, if the user starts filling the form you have to update the data along with session variable, then when the same user tries to access next time, the same session need to be loaded from the database. The session has to be identified from the cookie input like

identify the session using sid

sid = request.cookies.get(app.session_cookie_name)

followed by, you have to load the partial filled form data along with that particular session.

loading the session back

response.set_cookie(app.session_cookie_name, session.sid,
                            expires=self.get_expiration_time(app, session),
                            httponly=True, domain=domain)

The example code is already done by some GOD for you :)

I assume you are already aware of storing and retrieving the form data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM