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
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.
- Include template tag not working in django
- Removing the Label From Django's TextArea Widget
- Django queryset return single value
- Django Ajax "FORBIDDEN" error
- Clone an inherited django model instance