Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find value of HTML radio button in using Python and flask?

Tags:

python

html

php

web

So I've created the following form with radio buttons, that is submitted via "POST":

<form style="margin: auto">
            <label>
              <input type="radio" name="activity" value="0"/>sedentary
            </label>
            <label>
              <input type="radio" name="activity" value="1"/>lightly active (1-3 days a week)
            </label>
            <label>
              <input type="radio" name="activity" value="2"/>moderately active (3-5 days a week)
            </label>
            <br>
             <label>
              <input type="radio" name="activity" value="3"/>heavy exercise (6-7 days a week)
            </label>
            <label>
              <input type="radio" name="activity" value="4"/>very heavy exercise (exercising twice a day or working physical job)
            </label>
          </form>

My problem is that I don't know how to access the results of this in my Python code. I'm able to access values submitted via text forms on the same page, so I don't think my POST is the issue (I'm using Flask, so request.form.get("field") does the trick there). Research shows that people have previously suggested "request.form['activity']", but this results in a 404 error; people have also suggested "request.form.get('activity','1'), but this just returns a value of '1' whether or not the radio button is even pressed.

Any help would be appreciated!

like image 353
Lana Gorlinski Avatar asked Dec 07 '25 19:12

Lana Gorlinski


1 Answers

In your python code, put in a submit button within the form (let's name it "submit_button").

<input type="submit" name="submit_button">

Then use this:

if request.method='POST':
   if 'submit_button' in request.form:
      user_answer=request.form['activity']
      return user_answer

This will print whatever the user chose. I have used it in my flask web application, and it works.

This should also help you: flask handle form with radio buttons

like image 100
Devmonton Avatar answered Dec 09 '25 11:12

Devmonton