10

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',)
JPC
  • 8,096
  • 22
  • 77
  • 110

1 Answers1

20

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(),
        }
Wolkenarchitekt
  • 20,170
  • 29
  • 111
  • 174
Zach
  • 18,594
  • 18
  • 59
  • 68
  • thanks, I didn't know you could do that would it be the same thing for confirm password? – JPC Aug 20 '10 at 15:46
  • Since that field isn't in the model, you'll need to declare it separately...I'll update my answer – Zach Aug 20 '10 at 17:28
  • I'm still not sure I understand why I have to specify the PasswordInput as a widget to a CharField. They are both forms aren't they? Why can't I just use PasswordInput? Thanks! – JPC Aug 20 '10 at 17:36
  • 2
    There's a distinction between form fields and form widgets. You can think about it this way -- The form field decides how python should work with the field (validation, type, etc). The form widget is the HTML representation. In your case you want to deal with character input, but you want the HTML to show a password input. – Zach Aug 20 '10 at 17:46
  • On line three you have `form` as singular, and I'm assuming it's supposed to be plural – Alexander Bird Oct 02 '10 at 23:43