22

I have two questions concerning the clean method on a modelform. Here is my example:

class AddProfileForm(ModelForm):
        ...
        password = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'class':'form2'}))
        password_verify = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'class':'form2'}), label='Retype password')
        ...

        class Meta:
            model = UserModel
            fields=("username", "password", "password_verify", "first_name", "last_name", "date_of_birth", "biography", "contacts", )

        #called on validation of the form
        def clean(self):
            #run the standard clean method first
            cleaned_data=super(AddProfileForm, self).clean()
            password = cleaned_data.get("password")
            password_verify = cleaned_data.get("password_verify")

            #check if passwords are entered and match
            if password and password_verify and password==password_verify:
                print "pwd ok"
            else:
                raise forms.ValidationError("Passwords do not match!")

            #always return the cleaned data
            return cleaned_data
  1. Should I always call the standard clean method?

    cleaned_data=super(AddProfileForm, self).clean()
    
  2. Should I always return the cleaned_data variable?

    return cleaned_data
    
eykanal
  • 26,437
  • 19
  • 82
  • 113
rom
  • 3,592
  • 7
  • 41
  • 71

1 Answers1

26

For 1, Yes, if you want to make use of parent class's validators. See this explanation on the doc.

Warning

The ModelForm.clean() method sets a flag that makes the model validation step validate the uniqueness of model fields that are marked as unique, unique_together or unique_for_date|month|year.

If you would like to override the clean() method and maintain this validation, you must call the parent class’s clean() method.

For 2, yes, if data validates properly. Otherwise raise validation error.

Rohan
  • 52,392
  • 12
  • 90
  • 87
  • 1 / So if I don't call the parent class's clean method, the other fields won't be validated? In which case should this be useful ? (fields always must be validated, musn't they?) 2/ In my clean method, there can be a validation error but I return cleaned_data anyway! Is it a wrong way to do? – rom Aug 22 '13 at 04:30
  • 1
    @rom, Fields are validated in their own `field_clean()` method. `clean()` method is to validate any combination or multiple fields with values relating to one another. – Rohan Aug 22 '13 at 04:33
  • Ok so if I remove super(AddProfileForm, self).clean() it still works, no? Or it won't check the unique_together constraints (for example)? – rom Aug 22 '13 at 04:38
  • @rom, please read the answer to find out when it shall be called. – Rohan Aug 22 '13 at 04:41
  • Yes sorry, I just edited my previous comment, now I understand. What about the second point? (In my clean method, there can be a validation error but I return cleaned_data anyway! Is it a wrong way to do?) – rom Aug 22 '13 at 04:43
  • @rom, Either you return `cleaned_data` with removing invalid fields, setting up errors for fields or raise validation error. https://docs.djangoproject.com/en/dev/ref/forms/validation/ – Rohan Aug 22 '13 at 04:54
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/35963/discussion-between-rom-and-rohan) – rom Aug 22 '13 at 04:59
  • Can you use an example to show how the super function is called? ie: should I return it? Should I call it in the beginning of my code or the end? – isaaclw Nov 21 '13 at 01:30