[Django]-How to create password input field in django

59👍

You need to include the following in your imports;

from django import forms

96👍

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

18👍

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

14👍

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

from django.forms import CharField, Form, PasswordInput

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

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

4👍

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.

2👍

** Try to use this **

password1 = forms.CharField(widget=forms.PasswordInput(attrs={
    'class': 'input-text with-border', 'placeholder': 'Password'}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={
    'class': 'input-text with-border', 'placeholder': 'Repeat Password'}))

0👍

It’s very simple.

You should get password form field out of Meta class.

0👍

What was written by the OP at password = forms.Charfield(widget=forms.PasswordInput) was correct. It just does not belong in the class Meta: section. Instead, it should be above it, indented one level below class UserForm….

0👍

The solutions above works if the field is nullable. Using render_value will render the password into the input field and show the value as asterix placeholders.

Attention: This is great if you simply want to hide the password from users, but the password will be readable by using javascript.

class UserForm(forms.ModelForm):
    class Meta:
        model = Org
        fields = '__all__'

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

Edit:

Found a better solution without exposing the current password.
PASSWORD_ASTERIX_PLACEHOLDER will be set as value when loading the input. Before saving the model, it reverts the value to the old one if a user is not setting an explicit new password.

FormInput:

class PrefilledPasswordInput(PasswordInput):
    PASSWORD_ASTERIX_PLACEHOLDER: str = 'hidden-password'

    def __init__(self, attrs: dict = None, *args, **kwargs):
        if not attrs:
            attrs = {}
        attrs.setdefault('value', PrefilledPasswordInput.PASSWORD_ASTERIX_PLACEHOLDER)
        super().__init__(attrs=attrs, *args, **kwargs)

ModelField:

class PasswordCharField(models.CharField):
    def to_python(self, value):
        return super().to_python(value)

    def pre_save(self, model_instance, add):
        attr_name = self.get_attname()

        if not add:
            # Reset to old value if matching with PASSWORD_ASTERIX_PLACEHOLDER
            old_instance = self.model.objects.get(id=model_instance.id)
            current_value: str = getattr(model_instance, attr_name)
            if current_value == PrefilledPasswordInput.PASSWORD_ASTERIX_PLACEHOLDER:
                old_value: str = getattr(old_instance, attr_name)
                setattr(model_instance, attr_name, old_value)

        return super().pre_save(model_instance, add)

Your admin-(form):

class UserForm(forms.ModelForm):
    class Meta:
        model = Org
        fields = '__all__'

        widgets = {
            'password': PrefilledPasswordInput(),
        }

Your model:

class User(SomeBaseModel):
    ...
    password = PasswordCharField(max_length=32, null=False, blank=False)

0👍

from django import forms

class loginForm(forms.Form):
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Your userName'}))

    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'please enter password'}))

Leave a comment