Riaan
Riaan

Reputation: 195

ModelForm not finding field when submitting

I currently have this ModelForm for validating a new user registration:

class RegistrationForm(forms.ModelForm):
    email = forms.CharField(max_length=75, required=True)
    password = forms.PasswordInput()
    password_confirm = forms.PasswordInput()

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    def clean(self):
        if self.password != self.password_confirm:
            self.add_error('password_confirm', 'Passwords do not match.')

The user is required to confirm his password. When submitting this form I get the following error:

ValueError at /register

'RegistrationForm' has no field named 'password_confirm'.

I tried using the self.cleaned_data as well, but still get the same error.

The fields attribute cannot be removed nor can password_confirm be added to it.

How would one go about fixing this?

Upvotes: 0

Views: 274

Answers (2)

Sayse
Sayse

Reputation: 43300

You need to call the super clean first, and then you should use the cleaned data rather than the field.

def clean(self):
    cleaned_data = super(RegistrationForm, self).clean()
    if cleaned_data.get('password') != cleaned_data.get('password_confirm'):
        self.add_error('password_confirm', 'Passwords do not match.')

Upvotes: 2

Daniel Hepper
Daniel Hepper

Reputation: 29977

password and password_confirm are defined as widgets, not form fields.

Define two CharFields and pass the widget argument:

class RegistrationForm(forms.ModelForm):
    email = forms.CharField(max_length=75, required=True)
    password = forms.CharField(widget=forms.PasswordInput)
    password_confirm = forms.CharField(widget=forms.PasswordInput)

Upvotes: 2

Related Questions