Django密码字段输入尽管widget=forms.PasswordInput
声明显示为明文:
from django.contrib.auth.models import User
class LoginForm(forms.ModelForm):
# specify password type so that passwords show up as *******, not plaintext
# but this doesn't work if placeholder = ''
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ["username", "password"]
def __init__(self, *args, **kwargs):
# first call the 'real' __init__()
super(LoginForm, self).__init__(*args, **kwargs)
# then do extra stuff:
self.fields['username'].help_text = ''
self.fields['password'].widget = forms.TextInput(attrs={'placeholder': ''})
self.fields['password'].widget.attrs['class'] = 'form-control'
有趣的是,当我在模板中显示此表单时,password
值显示为明文而不是' ******'文本。但只有我添加'placeholder': ''
行。我检查了表单元素并发现当我添加'placeholder': ''
行时,type='password'
在呈现的HTML中的type='text'
元素中被更改为<input type='FOO'></input>
。
- &GT;如何防止这种情况发生,因此密码会继续显示为纯文本,而不会删除'placeholder': ''
行?
答案 0 :(得分:6)
您不应该使用forms.TextInput
作为密码字段。 Django provides a PasswordInput widget更合适。试试这个:
class Meta:
model = User
fields = ["username", "password"]
def __init__(self, *args, **kwargs):
# first call the 'real' __init__()
super(LoginForm, self).__init__(*args, **kwargs)
# then do extra stuff:
self.fields['username'].help_text = ''
self.fields['password'].widget = forms.PasswordInput(attrs={'placeholder': ''})
self.fields['password'].widget.attrs['class'] = 'form-control'
虽然您可以手动编辑字段的类型,但最好使用窗口小部件。