Sample of using SelectField in Flask

Example of use of SelectField to transfer data to/ from model and form/ template
mail@pastecode.io avatar
unknown
python
2 years ago
1.8 kB
4
Indexable
Never
class NewRecordForm(FlaskForm):
    coffee_bean = StringField('Coffee Bean', validators=[DataRequired(), Length(max=50)])
    roast_date = DateField('Roast Date', validators=[])
    brew_type = SelectField('Brew Type', choices=[(choice.name, choice.name) for choice in BrewType],
                            validators=[DataRequired()])
    grind_setting = DecimalField('Grind Setting', validators=[DataRequired(), NumberRange(min=0)], default=0)
    dose_size = DecimalField('Dose Size', validators=[DataRequired(), NumberRange(min=0)], default=18)
    output_size = DecimalField('Output Quantity', validators=[DataRequired(), NumberRange(min=0)], default=30)
    brew_time = DecimalField('Brew Time', validators=[DataRequired(), NumberRange(min=0)], default=25)
    tasting_notes = StringField('Tasting Notes', validators=[Length(max=200)])
    submit = SubmitField('Record Note')


@app.route('/record/new', methods=['GET', 'POST'])
@login_required
def new_record():
    form = NewRecordForm()
    if form.validate_on_submit():
        record = Record(
            taster=current_user,
            coffee_bean=form.coffee_bean.data,
            roast_date=form.roast_date.data,
            brew_type=form.brew_type.data,
            grind_setting=form.grind_setting.data,
            dose_size=form.dose_size.data,
            output_size=form.output_size.data,
            brew_time=form.brew_time.data,
            tasting_notes=form.tasting_notes.data
        )
        db.session.add(record)
        db.session.commit()
        flash('New record added!', 'success')
        # return redirect(url_for('user_tests', user_id=current_user.id))
        return redirect(url_for('home'))
    return render_template('new_record.html', title='New Record', form=form)