How to create password input field in django

112,568

Solution 1

You need to include the following in your imports;

from django import forms

Solution 2

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

Solution 3

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()

Solution 4

@DrTyrsa is correct. Don't forget your parentheses.

from django.forms import CharField, Form, PasswordInput

class UserForm(Form):
    password = CharField(widget=PasswordInput())

Solution 5

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

Share:
112,568
Dar Hamid
Author by

Dar Hamid

Updated on July 05, 2022

Comments

  • Dar Hamid
    Dar Hamid almost 2 years

    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 like this:

    class UserForm(ModelForm):
        class Meta:
            password = forms.CharField(widget=forms.PasswordInput)
            model = User
            widgets = {
                'password': forms.PasswordInput(),
            }
    

    But i am getting the following error: NameError: name 'forms' is not defined.

    I am using django version 1.4.0. I followed this link : Django password problems

    Still getting the same error. What should i do. Where am i getting wrong.Please help