Combining select field and integer field in flask

Viewed 217

I'm building a flask app and I am taking an input from the user that has a number and a choice from a menu (daily, weekly, monthly, annually) ..

That's currently my code for the HTML page

{% for field in form %} 
<div class="form-group">
  <label for="">{{field.label}}</label>
  {{field}} /
  <select name="frequency" id="">
    <option value="day">Day</option>
    <option value="week" selected>Week</option>
    <option value="month">Month</option>
    <option value="year">Year</option>
  </select>
</div>
{%endfor%}

python code where i need the value of select option menu:

 if form.validate_on_submit():
    for field in form:
        weight=getItemTotalGrams(getItemWeight(field.name), field.data, request.form.get('frequency'))

where getItemTotalGrams takes 3 integers and getItemWeight takes name of item and returns its weight. Item is an object that has 2 attributes, name and weight.

so, I am able to get the value from the field to use it in python later but i don't know how to get the value from the select option menu, so i thought about including it in the field but couldn't find a way to do so.

So my question is either:

  • is there a way where i can add a select field and integer field in WTF-Forms to connect the 2 input in one field?
  • or how to get the value of the select option menu to use it in python?
1 Answers

You may be able to combine multiple fields in a nested form. The FormField gives you the opportunity to do this. Several groups of this type can also be created in connection with a field of the FieldList type.

When the values are queried, a dict or a list of dicts is returned.

from flask_wtf import FlaskForm
from wtforms import FieldList, FormField, IntegerField, SelectField, SubmitField

class WeightForm(FlaskForm):
    weight = IntegerField()
    frequency = SelectField(
        choices=[
            ('day', 'Day'),
            ('week', 'Week'),
            ('month', 'Month'),
            ('year', 'Year'),
        ],
        default='week'
    )

    class Meta:
        # No need for csrf token in this child form
        csrf = False

class MyForm(FlaskForm):
    weights = FieldList(FormField(WeightForm), min_entries=1)
    submit = SubmitField()

@app.route('/example', methods=['GET', 'POST'])
def example():
    form = MyForm(request.form)
    if form.validate_on_submit():
        print(form.weights.data)
    return render_template('example.html', **locals())
<form method="post">
  {{ form.hidden_tag() }}
  {% for nested in form.weights -%}
  <div class="form-group">
    {{ nested.form.weight.label }}
    {{ nested.form.weight }}
    {{ nested.form.frequency }}
  </div>
  {% endfor -%}
  {{ form.submit }}
</form>
Related