Django密码问题

时间:2010-08-20 15:27:16

标签: django django-forms

我正在使用像这样的用户模型:

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

但密码字段显示为常规文本字段,而不是密码输入。如何确保显示密码字段?

我试过了:

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

但这也不起作用。

我也试图像这样添加一个确认密码字段,但这不会显示任何字段:

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 个答案:

答案 0 :(得分:20)

您错过了表单字段和表单小部件之间的区别。窗口小部件是字段的HTML表示形式。如果您使用的是Django 1.2,则可以使用以下语法:

编辑:更新以包含确认密码

class UserForm(forms.ModelForm):

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

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