I making an edit form using WTForms.
Now I want to make a default value that prepopulated from database in the TimeField form.
Here is the snippet of the code on the form above:
from wtforms.fields.html5 import TimeField
class ScheduleForm(Form):
start_at = TimeField('Start at',validators=[required()])
end_at = TimeField('End at', validators=[required()])
# ...
# ...
I try to call the obj
argument on the route that I called the form like this:
@app.route('/edit_schedule/<int:schedule_id>', methods=['GET', 'POST'])
def edit_schedule(schedule_id):
schedule = Schedule.query.filter_by(id=schedule_id).first()
print(schedule.start_at) # I got the value from database here
print(schedule.end_at) # I got the value from database here
form = ScheduleForm(obj=schedule) # call the obj argument
But the value on that field still didn't prepopulate, and then I try to make default value like this:
form = ScheduleForm(obj=schedule)
form.end_at.default = schedule.start_at
form.end_at.default = schedule.end_at
still didn't work, then I tried to add this line on the bellow the default value that I set above:
form.process()
Still didn't work, then I try to use lambda
:
form.start_at.default = lambda: db.session.query(Schedule.start_at).filter_by(id=schedule.id).first()
form.end_at.default = lambda: db.session.query(Schedule.end_at).filter_by(id=schedule.id).first()
No one on all of the ways above works.
So the point of my question is, how to set or prepopulate the default value on the TimeField..?
EDIT: here is the snippet of my model code:
class Schedule(db.Model):
__tablename__ = 'schedule'
id = db.Column(db.Integer, primary_key=True)
start_at = db.Column(db.Time())
end_at = db.Column(db.Time())
I figured out this by set default value on my template, like the line below:
{{ f.render_field(form.start_at, value=schedule.start_at) }}
{{ f.render_field(form.end_at, value=schedule.end_at) }}