欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

flask-wtf表单中PasswordField无法回传显示密码问题解决方法

程序员文章站 2022-07-09 21:53:16
...

flask-wtf中的PasswordField默认是无法将后端回传的密码数据显示出来的,可以通过修改PasswordInput来实现,在PasswordInput源码中有一个参数来决定能不能将密码显示
PasswordField源码

class PasswordField(StringField):
    """
    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()

PasswordInput源码

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(PasswordInput, self).__call__(field, **kwargs)

从PasswordInput的代码中可以知道hide_value决定了能不能显示密码,只需要将hide_value的值改为False就可以,可以改源码,但是不现实,下面通过继承来解决:

from wtforms.widgets.core import PasswordInput
from wtforms import PasswordField
from flask_wtf import FlaskForm

class MyPasswordField(PasswordField):
    widget = PasswordInput(hide_value=False)

使用方法:
class UserForm(FlaskForm):
    password = MyPasswordField()

亲测可用。

相关标签: 密码