Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a PasswordField in wtforms

Tags:

flask

wtforms

Is it possible to populate a password field in wtforms in flask?

I've tried this:

capform = RECAPTCHA_Form() 
capform.username.data = username
capform.password.data = password

The form is defined like:

class RECAPTCHA_Form(Form):
    username = TextField('username', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])
    remember_me = BooleanField('Remember me.')
    recaptcha = RecaptchaField()        

The template looks like this:

<form method="POST" action="">
  {{ form.hidden_tag() }}
  {{ form.username(size=20) }}
  {{ form.password(size=20) }}
  {% for error in form.recaptcha.errors %}
     <p>{{ error }}</p>
  {% endfor %}
  {{ form.recaptcha }}
  <input type="submit" value="Go">
</form>             

I have tried to change the PasswordField to a TextField, and then it works.

Is there some special limitation to populating PasswordFields in wtforms?

like image 712
J. P. Petersen Avatar asked Feb 14 '14 12:02

J. P. Petersen


1 Answers

Update: After looking through the WTForms docs I found an even better solution. There is a widget arg.

from wtforms import StringField
from wtforms.widgets import PasswordInput

class MyForm(Form):
     # ...

     password = StringField('Password', widget=PasswordInput(hide_value=False))

As yuji-tomita-tomita pointed out, the PasswordInput class (source) has an hide_value argument, however the constructor of PasswordField (source) does not forward it to the PasswordInput. Here is a PasswordField class that initializes PasswordInput with hide_value=False:

from wtforms import widgets
from wtforms.fields.core import StringField


class PasswordField(StringField):
    """
    Original source: https://github.com/wtforms/wtforms/blob/2.0.2/wtforms/fields/simple.py#L35-L42

    A StringField, except renders an ``<input type="password">``.
    Also, whatever value is accepted by this field is not rendered back
    to the browser like normal fields.
    """
    widget = widgets.PasswordInput(hide_value=False)
like image 77
fnkr Avatar answered Nov 07 '22 06:11

fnkr