mardi 4 juillet 2017

If/else variable assigned before if statement executed

The first instance of the number_of_discs receives data from another page and this value is visible in the form.

#####Results Page

@app.route('/results', methods=['GET', 'POST'])
def results():
        form=SendForm()

        number_of_discs = request.args.get('number_of_discs', '')

In the below code, If the function form.validate_on_submit() returns false, I want the number_of_discs variable to be reassigned the value that has been typed into the form to amended the original data.

#####Results Page

@app.route('/results', methods=['GET', 'POST'])
def results():
        form=SendForm()

        number_of_discs = request.args.get('number_of_discs', '')

        if form.validate_on_submit():
                        try:
                                models.insert(form)
                        except:
                                print ("hasn't worked")
                        else:
                                return redirect(url_for('success'))
        else:
                        number_of_discs = form.number_of_discs.data


        return render_template(
        'results.html', title='Results', number_of_discs=number_of_discs, form=form

    )

It works to an extent in that the variable is reassigned whatever is typed into the form. However, my problem now is that when I first load the page, the number_of_discs variable in the else statement seem to be initialized as the default value, rather than the first declaration of the number_of_discs variable (i.e. the data from the other page). So to summarize, the variable in the if/else statement seems to precede the variable assigned before/outside of it.

Aucun commentaire:

Enregistrer un commentaire