问题
I making a gender form using Flask-WTF, here is the snippet of my code:
class Gender(enum.Enum):
Male = 'Male'
Female = 'Female'
def __str__(self):
return self.value
gender = [(str(y), y) for y in (Gender)]
class EditStudentForm(Form):
gender = SelectField('Gender', choices=gender)
@app.route('/edit_student')
def edit_student():
student = Student.query.filter_by(id=student_id).first()
student_form = EditStudentForm()
# ... validate on submit
# ....
# ....
return render_template(student=student, student_form=student_form)
That code already works, included I can insert the data to the database.
But, if the current user gender value on database is Female, whenever I refresh the browsers, the form did not get the current value.
In HTML I want it to be like this:
// edit form
<form>
<input type="" value="currentUserValueFromDatabase">
</form>
I try to get current value using this way:
{{ f.render_field(student_form.gender, value=student.gender) }}
But it didn't prepopulate the current value from current user gender.
So what I want is to to display current value on selectfield or prepopulate the selectfield according to the current user value on the database.
回答1:
Pass student
to the EditStudentForm
as the obj
keyword argument, e.g.:
student_form = EditStudentForm(obj=student_form)
Why? From WTForms docs:
obj
– Ifformdata
is empty or not provided, this object is checked for attributes matching form field names, which will be used for field values.
When you construct the form when handling a GET
request, there is no form data, so it will use the object data.
回答2:
I think what you need is to set default value of gender field before you pass the form object to template. Try below.
@app.route('/edit_student')
def edit_student():
student = Student.query.filter_by(id=student_id).first()
student_form = EditStudentForm()
# set default
student_form.gender.default = student.gender
# process it to propagate the change.
student_form.process()
# ... validate on submit
# ....
# ....
return render_template(student_form=student_form)
来源:https://stackoverflow.com/questions/57830463/how-to-get-selectfield-current-value-with-flask-wtf