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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With