<< ALL BLOG POSTS

Django Forms: Handling form data in the POST

Table of Contents

Content in this blog updated on 8/6/2020.

Many times when creating forms in Django, we can use an instance of ourModelForm subclass, and simply call the save() method on that form object in order to persist the data to the database. But if we need to do something besides just saving the data, such as sending it elsewhere via an API call for example, or processing it before saving, we can access the validated data directly from the form.

Once the incoming data from the request has been put into an instance of our Form or ModelForm subclass, we use the form's is_valid() method to check the form for errors. This will call a series of methods on the form and its fields in order to check and/or clean the data. (We can customize these methods if we need to, but that is beyond the scope of this article.)  Notice we can pass form.errors as a message to display on the form, to give users feedback on why the validation failed:

form = OurCustomForm(request.POST)
if form.is_valid():
    # process data from form.cleaned_data, and/or call form.save()
else:
    messages.error(request, form.errors)
    # return form with entered data, display messages at the top

After a successful call to is_valid(), we can use the cleaned_data attribute to access the user's submitted data. Thanks to is_valid(), all the fields specified within the form will be present, even if the HTML form doesn't return a field because it was submitted while the input element was empty or had no choice selected.

For multiselects or inlines (one-to-many fields) that have multiple values, the value returned will be a list.

Uploaded files aren't part of the cleaned_data, but are accessed through the request's FILES attribute:

portrait_file = request.FILES.get('portrait')

For the full details, make sure to look at the official Django documentation on how to use forms.

Related Posts
How can we assist you?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.