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()
親測可用。