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