15

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)

2 Answers 2

31

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
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for mentioning Django will raise an AttributeError if you try to access cleaned_data before calling is_valid() Fun fact: It still does this 6 years later...
@pentix Yip. You think that perhaps they might have used a FormNotValidated error?
It still does 3 more years later
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.