neilH
neilH

Reputation: 3438

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 seems 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.

Upvotes: 0

Views: 64

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78554

You can avoid overwriting that default value by executing the current if/else only when the request is 'POST':

@app.route('/results', methods=['GET', 'POST'])
def results():
   ...
   number_of_discs = request.args.get('number_of_discs', '')
   if request.method == 'POST':
      if form.validate_on_submit():
         ...
      else:
         ...

Upvotes: 1

Related Questions