Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle data between forms

If I have a registration with 3 steps, that will use 3 forms.

Something like this, just to demonstrate:

@app.route('/form/step1', methods=['GET', 'POST'])
def form_step1():
    form = form_step_1(request.form)
    ...validate()...
    return render_template('register.html', form=form)

@app.route('/form/step2', methods=['GET', 'POST'])
def form_step2():
    form = form_step_2(request.form)
    ...validate()...
    return render_template('register.html', form=form)

@app.route('/form/step3', methods=['GET', 'POST'])
def form_step3(): 
    form = form_step_3(request.form)
    ...validate()...
    return render_template('register.html', form=form)

What is the correct way to handle data between these three steps? All data should be committed to database at the end of the step 3. But a back action between the forms should populate again the previous form.

Use sessions for this purpose seems bad.

like image 345
user455318 Avatar asked Sep 30 '22 14:09

user455318


1 Answers

I would personally suggest using the session object to pass data from one form to another. If you have a small amount of data then you can get away with just using the cookie implementation that flask has. Otherwise, you can override the default sessions object to store sessions data server side using Redis. This lets you use session objects without paying the price of storing lots of data in cookies. This means you can do something like

@app.route('/form/step1', methods=['GET', 'POST'])
def form_step1():
    form1 = form_step_1(request.POST)
    user_id = current_user.user_id # If you're using flask-login
    ...validate()...
        # dictionary that holds form1, form2, etch
        form_data = {"form1": form1, "form2": None, "Form3"=None} 
        flask.session[user_id] = form_data
        redirct_to(url_for("form_step2"))
    return render_template('register.html', {'form':form1})  

@app.route('/form/step2', methods=['GET', 'POST'])
def form_step2():
    form1 = session[user_id][form1]
    # A simpler way than passing the whole form is just the data 
    # you want but for this answer I'm just specifying the whole form.
    form = form_step_2(form1)
    user_id = current_user.user_id # If you're using flask-login 
    ...validate()...
        # dictionary that holds form1, form2, etch
        flask.session[user_id]["form2"] = form2
        redirct_to(url_for("form_step3"))
    return render_template('register.html', form=form)
like image 93
AlexLordThorsen Avatar answered Oct 02 '22 14:10

AlexLordThorsen