4

I have a simple Django model:

class Remote(models.Model):
    password = models.CharField(max_length=256, blank=True)

and admin.py:

class RemoteForm(forms.ModelForm):
    class Meta:
        widgets = {
            'password': forms.PasswordInput(),
        }

class RemoteAdmin(ForStaffModelAdmin):
    form = RemoteForm

admin.site.register(Remote, RemoteAdmin)

If I open the change_view for an instance in the django admin, then the password field is empty. I checked the db: the instance has a password.

Why is PasswordInput empty?

I would like to see "********"

guettli
  • 25,042
  • 81
  • 346
  • 663

2 Answers2

8

Don't ask me why, but this works. I added render_value=True.

class RemoteForm(forms.ModelForm):
    class Meta:
        widgets = {
            'password': forms.PasswordInput(render_value=True),
        }

Docs of PasswordInput

guettli
  • 25,042
  • 81
  • 346
  • 663
  • Lifesaver! Thank you for that answer – umat Feb 04 '20 at 14:43
  • @umat if it helped, then please upvote the question and the answer. Thank you – guettli Feb 05 '20 at 07:58
  • This does work, but be aware that the data, as shown in the password field in the database, will now be visible if you inspect the element. So if it's plain-text it will be plain-text in the forms value field. If it's a hash, the hash will display in forms value field. – ThatGuyRob Jan 06 '22 at 22:05
2

The password widget Input is for your security. by default render_value = False. That means if you get the error in forms and form(request.POST) rendered with errors at that time all inputs are populated with data you added before pressing the submit button. But the input type="password" field is not populated with previously added value. You see blank input once you enter submit and make a POST request and when your error form is rendered with old (request.POST) data.

  • This render_value parameter is by default False for the widget PasswordInput in your forms.py
  • If you don't want this behavior you can simply make it render_value = True in forms.py after that when the error form is rendered back you can see your input type="password" also populated with previous data you added before submitting the form.

Here, Note one thing you see the data like "********" in the password input because of HTML behavior. This is not related to Django, If you want to see the actual password inspect the element and change input type="password" to input type="text".

See the code below...

forms.py

class SchoolUserModelForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(render_value=True)

OR

class SchoolUserModelForm(forms.ModelForm):
    class Meta:
        widgets = {
            'password': forms.PasswordInput(render_value=True),
        }

Hope it helps everyone.