How to create password input field in django

前端 未结 9 667
春和景丽
春和景丽 2020-12-28 11:19

Hi I am using the django model class with some field and a password field. Instead of displaying regular plain text I want to display password input. I created a model class

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 12:12

    Since this question was asked a couple years ago, and it is well indexed on search results, this answer might help some people coming here with the same problem but be using a more recent Django version.

    I'm using Django 1.11 but it should work for Django 2.0 as well.


    Taking into account that you using a model user I will assume that you are using the default User() model from Django.

    Since the User() model already has a password field, we can just add a widget to it.

    from django import forms
    from django.contrib.auth.models import User
    
    # also, it will work with a custom user model if needed.
    # from .models import User
    
    
    class UserRegistrationForm(forms.ModelForm):
    
        class Meta:
            model = User
            fields = ['username', 'password']
    
            widgets = {
                # telling Django your password field in the mode is a password input on the template
                'password': forms.PasswordInput() 
            }
    

    Check the docs

    I'm fairly new to Django, if my answer was not accurate enough, please let us know, I'd be happy to edit it later on.

提交回复
热议问题