Search code examples
flaskflask-sqlalchemyflask-wtforms

What is the best way to have a user enter a time in Flask WT Forms?


I want the user to select a military time within a Flask Form. So far I have a list of hours and a list of minutes. I also use SqlAlchemy and want the data saved into a DateTime column.

hours = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13",
            "14","15","16","17","18","19","20","21","22","23"]
minutes = ["00","05","10","15","20","25","30","35","40","45","50","55"]

time_hours = SelectField('Hours', choices=hours)
time_minutes = SelectField('Minutes', choices=minutes)

I could use two separate SelectFields, one for hours and the other for minutes, and combine them within the view, finally saving them into a DateTime field. That will complicate things when I set up an edit page and try to fill in the form's data with the data stored in the database. Does anyone know if there is a "proper" way to select a time within Flask WT Forms?


Solution

  • You could install the package WTForms-Components and use TimeField as follows:

    from wtforms_components import TimeField
    
    class YourForm(FlaskForm):
        ...
        time = TimeField('Time')
        
    

    It will render something like this

    enter image description here