How to create password input field in django

怎甘沉沦 提交于 2019-11-30 02:37:45
DrTyrsa

You need to include the following in your imports;

from django import forms

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

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

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

from django.forms import CharField, Form, PasswordInput

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

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

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.

It's very simple.

You should get password form field out of Meta class.

Fr George

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....

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!