Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cleaned_data on forms in django

What is the point in setting cd = form.cleaned_data before passing the input values of a POST/GET submission?

What is the point in this and why is it necessary? (if it is so)

like image 989
David542 Avatar asked May 08 '11 02:05

David542


2 Answers

It is not necessary to use the .cleaned_data attribute of a form before passing the input values, it will raise an AttributeError if you do it before calling .is_valid() in a bound form or if you try to access it in an unbound form, read more about Form.cleaned_data .

Also, it is usually a good idea to abstract the use of the form's data in a form method in order to encapsulate logic

In your views, the traditional way you should be using forms is like this:

if request.method == 'POST':
  form = MyForm(request.POST) # Pass the resuest's POST/GET data
  if form.is_valid():         # invoke .is_valid
    form.process() # look how I don't access .cleaned_data in the view

in your form:

class MyForm(forms.Form):
  my_field = forms.CharField()

  def process(self):
    # Assumes .cleaned_data exists because this method is always invoked after .is_valid(), otherwise will raise AttributeError
    cd = self.cleaned_data 
    # do something interesting with your data in cd
    # At this point, .cleaned_data has been used _after_ passing the POST/GET as form's data
like image 197
Jj. Avatar answered Nov 13 '22 21:11

Jj.


Once is_valid() returns True, you can process the form submission safe in the knowledge that it conforms to the validation rules defined by your form. While you could access request.POST directly at this point, it is better to access form.cleaned_data. This data has not only been validated but will also be converted in to the relevant Python types for you.

Processing the data from a form

like image 22
solartic Avatar answered Nov 13 '22 19:11

solartic