yesmen
yesmen

Reputation: 123

Checkboxes in Python Flask if nothing selected

I want checkboxes on my website. If these checkboxes are selected, an output should be output. If the checkboxes are not selected, nothing should happen. I almost made it. But I don't know how to program that if the checkbox is not selected, nothing happens

Here is my try in my Python (flask):

@app.route("/checkbox", methods = ['GET','POST'])
def checkbox_value():
 if request.method == 'POST':   
      if request.form.get("checkbox1"):
          checkbox_data_1 = some_data
          checkbox_title_1 = some_other_data
      else:
          #nothing should happen.
      if request.form.get("checkbox2"):
          checkbox_data_2 = some_data
          checkbox_title_2 = some_other_data
      else:
          #nothing should happen.

return render_template('index.html', checkbox_data_1= checkbox_data_1, checkbox_title_1= checkbox_title_1, checkbox_data_2= checkbox_data_2, checkbox_title_2= checkbox_title_2  )

If I don't select a checkbox I get this error message "UnboundLocalError: local variable 'checkbox_data_1' referenced before assignment"

Upvotes: 0

Views: 1022

Answers (1)

wxker
wxker

Reputation: 1896

That error means that you are referencing a variable before it is declared.

In the case where checkbox 1 is not selected, you will be referencing checkbox_data_1 and checkbox_title_1 in the return statement when they have not been declared since the code does not enter the first if block. Same goes for checkbox 2.

To resolve this, simply initialize them with some default value. I went ahead and declared it as None but go ahead and change it to what works for you.

@app.route("/checkbox", methods = ['GET','POST'])
def checkbox_value():
    checkbox_data_1 = None  
    checkbox_title_1 = None  
    checkbox_data_2 = None
    checkbox_title_2 = None  
    if request.method == 'POST':   
        if request.form.get("checkbox1"):
            checkbox_data_1 = some_data
            checkbox_title_1 = some_other_data
        if request.form.get("checkbox2"):
            checkbox_data_2 = some_data
            checkbox_title_2 = some_other_data

    return render_template('index.html', checkbox_data_1= checkbox_data_1, checkbox_title_1= checkbox_title_1, checkbox_data_2= checkbox_data_2, checkbox_title_2= checkbox_title_2  )

Also, there is no need for an else block if you're going to leave it empty

Upvotes: 2

Related Questions