在wtforms中填充PasswordField

时间:2014-02-14 12:18:14

标签: flask wtforms

是否可以在烧瓶中的wtforms中填写密码字段?

我试过这个:

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

表单定义如下:

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

模板如下所示:

<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>             

我尝试将PasswordField更改为TextField,然后就可以了。

在wtforms中填充PasswordFields有一些特殊限制吗?

3 个答案:

答案 0 :(得分:3)

我在Flask和Flask应用程序中发现的一些东西是源代码是文档。实际上,默认情况下,您无法填充该字段。您可以传递参数hide_value以防止此行为。

这是一个很好的电话,因为如果您可以填充该字段,您可以访问原始密码......这可能很危险。

class PasswordInput(Input):
    """
    Render a password input.

    For security purposes, this field will not reproduce the value on a form
    submit by default. To have the value filled in, set `hide_value` to
    `False`.
    """
    input_type = 'password'

    def __init__(self, hide_value=True):
        self.hide_value = hide_value

    def __call__(self, field, **kwargs):
        if self.hide_value:
            kwargs['value'] = ''
        return super(

答案 1 :(得分:2)

我相信有一种更简单的方法来访问密码字段的数据,而不使用hide_value。在您的视图中,只需将请求数据作为参数添加到表单的构造函数中:

from flask import request    

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

这应该使密码输入可用于验证,并在需要时用于测试。

答案 2 :(得分:2)

更新:浏览WTForms文档后,我找到了更好的解决方案。 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))

正如yuji-tomita-tomita指出的那样,PasswordInput类(source)有一个hide_value参数,但是PasswordField的构造函数(source )不会将其转发给PasswordInput。这是一个PasswordField类,用PasswordInput初始化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)