How to create password input field in django

前端 未结 9 629
春和景丽
春和景丽 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 11:59

    It's very simple.

    You should get password form field out of Meta class.

    0 讨论(0)
  • 2020-12-28 12:00

    The widget needs to be a function call, not a property. You were missing parenthesis.

    class UserForm(ModelForm):
        password = forms.CharField(widget=forms.PasswordInput())
        class Meta:
            model = User
    
    0 讨论(0)
  • 2020-12-28 12:02

    You need to include the following in your imports;

    from django import forms
    
    0 讨论(0)
  • 2020-12-28 12:05

    I did as a follow without any extra import

    from django import forms
    class Loginform(forms.Form):
        attrs = {
            "type": "password"
        }
        password = forms.CharField(widget=forms.TextInput(attrs=attrs))
    

    The idea comes form source code: https://docs.djangoproject.com/en/2.0/_modules/django/forms/fields/#CharField

    0 讨论(0)
  • 2020-12-28 12:10

    Why not just create your own password field that you can use in all your models.

    from django import forms 
    
    class PasswordField(forms.CharField):
        widget = forms.PasswordInput
    
    class PasswordModelField(models.CharField):
    
        def formfield(self, **kwargs):
            defaults = {'form_class': PasswordField}
            defaults.update(kwargs)
            return super(PasswordModelField, self).formfield(**defaults)
    

    So now in your model you use

    password = PasswordModelField()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题