Why does data need cleaning?

Eventually, you need to get the cleaned data from the form. Does this mean that the values that the user entered were not clean? Yes, for two reasons.

First, anything that comes from the outside world should not be trusted initially. Malicious users can enter all sorts of exploits through a form that can undermine the security of your site. So, any form data must be sanitized before you use it.

Best Practice

Never trust the user input.

Secondly, the field values in request.POST and request.GET are just strings. Even if your form field can be defined as an integer (say, age) or date (say, birthday), the browser would send them as strings to your view. Invariably, you would like to convert them to the appropriate Python types before use. The form class does this conversion automatically for you while cleaning.

Let's see this in action:

>>> fill = {"name": "Blitz", "age": "30"} 
 
>>> g = PersonDetailsForm(fill) 
 
>>> g.is_valid() 
 True 
 
>>> g.cleaned_data 
 {'age': 30, 'name': 'Blitz'} 
 
>>> type(g.cleaned_data["age"]) 
 int 

The age value was passed as a string (possibly from request.POST) to the form class. After validation, the cleaned data contains the age in the integer form. This is exactly what you would expect. Forms try to abstract away the fact that strings are passed around and give you clean Python objects that you can use.

Always use the cleaned_data from your form rather than raw data from the user.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset