Django password problems

心不动则不痛 提交于 2019-12-20 19:41:29

问题


I'm using a modelform for User like so:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username','password','email',)

but the password field shows up as a regular textfield, not a password input. How do I make sure it shows a password field?

I tried this:

class UserForm(forms.ModelForm):
    username = forms.CharField(max_length = 15, min_length = 6)
    password = forms.PasswordInput() 
    class Meta:
        model = User
        fields = ('username','password','email',)

but that doesn't work either.

I'm also trying to add a confirm password field like so, but this causes no fields to be displayed:

class UserForm(forms.ModelForm):
    username = forms.CharField(max_length = 15, min_length = 6)
    password = forms.PasswordInput()
    cpassword = forms.PasswordInput()

    def clean(self):
        if self.cleaned_data['cpassword']!=self.cleaned_data['password']:
            raise forms.ValidationError("Passwords don't match")

    class Meta:
        model = User
        fields = ('username','password','cpassword','email',)

回答1:


You're missing the difference between form fields and form widgets. The widget is the HTML representation of the field. If you're on Django 1.2 you can use this syntax:

EDIT: Update to include confirm password

class UserForm(forms.ModelForm):

    confirm_password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ('username','password','email',)
        widgets = {
            'password': forms.PasswordInput(),
        }


来源:https://stackoverflow.com/questions/3532354/django-password-problems

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