问题
I am rather new to WTForms, Flask-WTF. I can't figure out how to simply add the HTML5 attribute "autofocus" to one of the form field, from the form definition. I would like to do that in the Python code, not in the Jinja template. Here is what I have :
class NameForm(Form):
name1 = StringField("Nom d'utilisateur :",
validators=[Required(), Length(1, 16)])
pwd1 = PasswordField("Mot de passe :",
validators=[Required(), Length(1, 16)])
mail1 = StringField("Compte GMail du calendrier :",
validators=[Required(), Email()])
submit = SubmitField('Envoyer')
I just want to add the "autofocus" attribute to the field "name1".
I tried this in the route :
@app.route('/', methods=['GET', 'POST'])
def form():
name1 = None
pwd1 = None
mail1 = None
msg = None
# Tests
Name_Form_kwargs = {"name1": "" ,"autofocus" :"true"}
Name_Form = NameForm(**Name_Form_kwargs)
print Name_Form.name1
#
form = NameForm()
.....
But this only changes the field value and do not add any attribute :
<input id="name1" name="name1" type="text" value="">
I read a lot of answers from SO and tried all kind of solutions, but I'm stuck. Thanks for your help.
回答1:
I have found, that you can add the argument render_kw to your field in your form class where you can add all the keywords for your rendering, including autofocus.
So what I have now in my form class is:
class CheckForm(FlaskForm):
"""
Check-in or check-out users.
"""
checkmode = RadioField('checkmode', validators=[DataRequired()], choices=[('in', 'Check-In'), ('out', 'Check-Out')])
datainput = StringField('Name', validators=[DataRequired()], render_kw={'autofocus': True})
submit = SubmitField('Submit')
This renders just as expected with wtf.quick_form() and places the cursor in the StringField on load with wtforms version 2.1 and flask-wtf version 0.14.2.
回答2:
It has to be done by the file.html Jinja template. So declare it as below:
{{ form.input1(autofocus=true) }}
That will put the single autofocus
attribute into your html code.
回答3:
only you use:
autofocus=true
in your file.html
回答4:
You can't do it through the Python definition of the form, not that I've been able to find. The way to do it is to add some Javascript to focus on the field you want when the page is loaded.
I've got a project that uses Flask-Bootstrap (so jQuery is already getting loaded) which means that your templates need to include a
{% block scripts %}{% endblock %}
In your form template, put the following at the end:
{% block scripts %}
{{ super() }}
<script type="text/Javascript">
$("input#my_focus_field_id").focus()
</script>
{% endblock %}
来源:https://stackoverflow.com/questions/31969070/wtforms-how-to-add-autofocus-attribute-to-a-stringfield