Although its an old post, if you want to apply checks on more than 1 field of the same form / model, use clean() . This method returns the dictionary cleaned_data strong>.
To show errors to users, you can use the add_error(<fieldname>, "your message") method. This will show errors along with the field name, and not on top of the form. An example is shown below:
add_error() automatically removes the field from the dictionary cleaned_data strong>, you do not need to delete it manually. Also you do not need to import anything to use this.
documentation here
def clean(self): if self.cleaned_data['password1'] != self.cleaned_data['password2']: msg = 'passwords do not match' self.add_error('password2', msg) return self.cleaned_data
If you just want validation in the same form / model field to use clean_<fieldname>() . This method will take values ββfrom the dictionary cleaned_data strong>, and then you can check for logical errors. Always return a value after completing the logic check.
def clean_password(self): password = self.cleaned_data['password'] if len(password)<6: msg = 'password is too short' self.add_error('password', msg) return password
sgauri
source share