0

so im making a Flask app where a user uploads a spreadsheet and then can play with the parameters of that spreadsheet on a html page. One parameter is a value which can only be 1, 2 or 3. The user is able to change this value by selecting a radio button with these options.

This all works fine but i would like the default value of the radio button to be whatever was in the initial spreadsheet that the user uploaded.

my idea was to do something like this:

main.py

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

    value = 2
    value_dict = {'1': 1==value, '2': 2==value, '3': 3==value}
    
    return render_template('home/sheet.html', value_dict)

sheet.html

<div>
    <input type="radio" id="n1" name="nyears" value=1 checked={{value_dict["1"]}}>
        <label for="n1"> 1 </label>

    <input type="radio" id="n2" name="nyears" value=2 checked={{value_dict["2"]}}>
        <label for="n2"> 2 </label>

    <input type="radio" id="n3" name="nyears" value=3 checked={{value_dict["3"]}}>
        <label for="n3"> 3 </label>
</div>

But unfortunately, any use of the 'checked' attribute will check the box (in this case number 3, as it is the last to use the checked attribute). It seems that the only way to have a default checked value is to only use the checked attribute on one input line.

Any help getting this to work will be greatly appreciated Thanks in advance!

Callum Brown
  • 161
  • 9
  • 1
    Put `checked` in a statement: https://stackoverflow.com/questions/14214942/jinja2-shorthand-conditional – ivvija May 09 '22 at 13:04
  • thank you for the reply - extremly sorry but could you post an example code based on my example above? Im quite new to this – Callum Brown May 09 '22 at 13:06

1 Answers1

1

You need to set the variable name in render_template by passing it as keyword:

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

    value = 2
    value_dict = {'1': 1==value, '2': 2==value, '3': 3==value}
    
    return render_template('home/sheet.html', value_dict=value_dict)
<div>
    <input type="radio" id="n1" name="nyears" value=1  {{ 'checked' if value_dict["1"] else '' }} >
        <label for="n1"> 1 </label>

    <input type="radio" id="n2" name="nyears" value=2  {{ 'checked' if value_dict["2"] else '' }} >
        <label for="n2"> 2 </label>

    <input type="radio" id="n3" name="nyears" value=3  {{ 'checked' if value_dict["3"] else '' }} >
        <label for="n3"> 3 </label>
</div>
ivvija
  • 482
  • 4
  • 9