Hillary Sanders Hillary Sanders - 2 months ago 32
Python Question

Django password field input showing up as plaintext despite forms.PasswordInput declaration

Django password field input showing up as plaintext despite

widget=forms.PasswordInput
declaration:

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'


So interestingly, when I surface this form in a template, the
password
value shows up as plaintext instead of '******' text. But only if I add the
'placeholder': ''
line. I inspected the form element and figured out that when I added the
'placeholder': ''
line,
type='password'
was being changed to
type='text'
in the
<input type='FOO'></input>
element in the rendered HTML.

--> How do I keep this from happening, so passwords continue to show up as plaintext, without removing my
'placeholder': ''
line?

Answer

You should not be using forms.TextInput for your password field. Django provides a PasswordInput widget that is more appropriate. Try this:

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'

While you can edit the type of the field manually, it's better convention to use the widget.

Comments