Django密码字段输入尽管form.PasswordInput声明显示为明文

时间:2016-09-20 16:58:04

标签: python django forms

Django密码字段输入尽管widget=forms.PasswordInput声明显示为明文:

forms.py

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值显示为明文而不是&#39; ******&#39;文本。但只有我添加'placeholder': ''行。我检查了表单元素并发现当我添加'placeholder': ''行时,type='password'在呈现的HTML中的type='text'元素中被更改为<input type='FOO'></input>

- &GT;如何防止这种情况发生,因此密码会继续显示为纯文本,而不会删除'placeholder': ''行?

1 个答案:

答案 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'

虽然您可以手动编辑字段的类型,但最好使用窗口小部件。