1

I am new to Python and Flask programming. In my website development, I am trying to get the value that is selected from a bootstrap single button dropdown into the python code. This is what I tried -

Python code - routes.py

   @app.route("/index", methods=['GET','POST'])
   def index():
       form = IndexForm()
       data = ['Red', 'Green', 'Blue']
       if form.validate_on_submit():
           posts = get_data(color=request.form.get("color_dropdown"))
           return render_template('index.html', title='My Form', form=form, posts=posts, data=data) 

       return render_template('index.html', title='My Form', form=form, data=data)

HTML code - index.html

The dropdown is populated as expected with the elements of the list 'data'.

   <div class="dropdown">
        <div class="input-group-btn">
            <button class="btn btn-info btn-md dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="color_dropdown" >
            Select Color
            <span class="caret"></span>
            </button>
            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                {% for datum in data %}
                   <a class="dropdown-item" href="#">{{ datum }}</a>
                {% endfor %}
            </div>
        </div>
    </div>

So far so good. enter image description here

When i select a color option eg. 'Red', it is seen on the button too, using the jscript -

   <script>
        $(".dropdown-menu a ").click(function(){
            $(this).parents(".input-group-btn").find('.btn').text($(this).text());
        });
    </script>

And it looks like above. enter image description here

Now, when i try to retrieve the value of the selected option from the dropdown using - color=request.form.get("color_dropdown") it is always returning None.

Form Class - forms.py

   class IndexForm(FlaskForm):
      car = StringField('Car', validators=[DataRequired()])
      submit = SubmitField('Submit')

How can i get the value of the selected option ('Red' in the above case) in routes.py and assign it to color variable? Thanks in advance.

Ira
  • 547
  • 4
  • 13
  • Why not just prepare a list of urls to match the list of colors. The url would contain the color as a parameter and you would thus pass it to the view `def index()`. See for example [this stackoverflow discussion](https://stackoverflow.com/questions/24892035/how-can-i-get-the-named-parameters-from-a-url-using-flask). – Mike O'Connor Jan 19 '20 at 08:14

1 Answers1

1

I have accomplished more or less what you're looking for without JS by using the syntax variable = form_name.form_field.data (in routes.py).

I hope this helps.

Edited:

Probably best to access the form's attributes directly. Also,

forms.py:

class IndexForm(FlaskForm):
      car_options = SelectMultipleField(
                 u'Select Color', choices=[('Red', 'red'), ('Blue', 'blue'), ('Green', 'green')], size=1)
      submit = SubmitField('Submit')

index.html:


    <form action='/' , method='POST'>
        {{form.hidden_tag() }}
        <button class="btn btn-info btn-md dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="color_dropdown" >
            Select Color
            <span class="caret"></span>
            </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
        {% for subfield in form.choices %}
              <a class="dropdown-item" href="#">
              {{ subfield.label }}
              </a>
        {% endfor %}
        </div>
        <div class="submit">
            {{ form.submit(class="btn btn-info") }}
        </div>
    </form>

routes.py:

@app.route("/index", methods=['GET','POST'])
   def index():
       form = IndexForm()
       if form.validate_on_submit():

           color_choice = form.car_options.data
           if color_choice = 'green':
               print("Sick bro")
           else:
               pass

           #since you can access the choices as an attribute of the form,
           #there is no need to define "posts" (I named it color choice) unless 
           #you are going to use it here.

           return redirect('index.html')

       return render_template('index.html', title='My Form', form=form, data=data)

Peter Charland
  • 409
  • 6
  • 18