Clean multiple fields in DJango form

Django packs a ton of cleaning methods in the box which includes validating against field types, length of inputs, etc. It also lets you add custom validation rules for entier form or for individual fields. A few tips for it.

Advert

Django provides two way to add custom validation rules to a form.

  1. clean() : If added as a form sub-class, lets you access and validate all fields in the form.
  2. clean_<fieldname>() : Lets you define validation method for the , it's added as sub-class in form.

Usign clean()

You can have your custom validation code in these classes. Once you detected an invalid data raise error. Use this method if you need to deal with multiple inputs.

raise forms.ValidationError("<error messge>", code="<error_code>",)

These functions gives the absolute power to deal with forms. Example usage:

class ContactForm(forms.Form):
 # Form fields
 def clean(self):
  if field < 100:
   raise forms.ValidationError("you can't go below 100", code="field1",)
  return  self.cleaned_data

Using clean_<fieldname>()

If your requirement is to validate a single field this is right solution. It allows all the functions you can do with the clean() but restricts access only to the single field.
Example Usage

class ContactForm(forms.Form):
 # Form fields
 # user_name is the form field 
 def clean_user_name(self):
  user_name = self.cleaned_data['user_name']
  if user_name is None:
   raise forms.ValidationError("Give me a username", code="user_name",)
  return  user_name

Flow of control

You don't have to go for a long vacation to be in a situation where you have to use clean_<fieldname>()& clean() together or clean_<fieldname>() multiple times inside a same form. Here's how they get executed.

  • All clean_<fieldname>() are executed before executing the main clean() function.
  • Once a clean_<fieldname>() is executed the field is removed from the cleaned_data.

If using multiple clean method make sure you check if field exists in the cleaned_data before you grab it, it can result in KeyError if the fields clean method removed it.

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. Software Testing

     
  2. Best WordPress Themes For Photographers And Photography

     
  3. Problems That Affect Conversion Rates

     
  4. Best WordPress Themes in 2017

     
  5. SEO in 2017: Mobile optimization as a competitive advantage

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.