How to get a Django Prepopulated Model Form for User to *not* populate password

761 views Asked by At

I have a ModelForm for the User model that I want to use to allow the user to update some of their settings (first name, last name, email, and, of course, password). It's a very basic form and I did the UserForm(instance=user) so the user would see their current values. However, it's populating the password field, which seems kind of crazy (especially since it's the hashed value - not that I want their actual value to be shown). I would prefer the password is just left empty (I've added an extra field to the model form so they must enter their new password twice).

Is there a way to specify that this field should not be populated? It also seems to be defaulting to type='text' (looking at the html source) instead of type='password'.

Thanks

2

There are 2 answers

0
Raja Simon On BEST ANSWER

Django ModelForm have widgets attribute and also you can use forms widgets PasswordInput for password field

let's assume you already have working view..so I skip the full view here

#views.py
form = UserForm(request.POST, instance = user)

set the widgets like

#forms.py

widgets = {
            'password':forms.PasswordInput(render_value = True),
        }

And using the init to define the initial value

def __init__(self, user, *args, **kwargs):
    user = kwargs.pop('instance')
    super(UserForm, self).__init__(*args, **kwargs)
    self.fields['username'].initial = user.username
    self.fields['first_name'].initial = user.first_name
    self.fields['last_name'].initial = user.last_name
    self.fields['email'].initial = user.email
    self.fields['password'].initial = user.password
0
ruddra On

You can override the __init__ function of the form class so that each time the form class(constructor) is called, if the form is used for editing data, it will not show set any pre populated data for password. For example:

class SomeModelForm(forms.ModelForm):
   ...
   def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
      if self.initial:
          self.fields['password'].initial = ''
          self.fields['retype_password'].initial = ''