Thanks for filling out the form! A Six Feet Up representative will be in contact with you soon.

Have a technical question? Ask a Sixie!

<< All Blog Posts
Django Forms: Handling form data in the POST

Django Forms: Handling form data in the POST

Many forms created in Django are simply for creating content based on a model, and won't require any special processing. But some forms you create will require custom changes to be made with the data sent to the form. Here are some tips for getting that data in the view.

In a Class-Based View subclassing FormView, this can be done within a post function. If you have a function-based view, check if request.method == 'POST'.

If the view is connected to a defined Form, use the built-in function is_valid to check the form for errors. Notice you can pass form.errors as a message to display on the form, to give users feedback on why the validation failed:

form = ProfileForm(request.POST, instance=request.user)
if form.is_valid:
    # process data, return next page
else:
    messages.error(request, form.errors)
    # return form with entered data, display messages at the top

Next, make a copy of the form data:

data = request.POST.copy()

Then you can use data to access the user's submitted data.

  • To get data from a specific field, use what is set in the name attribute to call the field. This is not always the same as id.
  • Use .get() to access the field, because if the field is left empty in the form, it will not be in data, and None will be returned.

Examples:

name = data.get('name')
age = data.get('age')

Checkboxes will get the value from the checked option, or 'on' if there is no value

married = data.get('married')

Radio buttons will return the value of the selected option

kids = data.get('no_of_kids')

For multiselects or inlines (one-to-many fields) that have multiple values, use .getlist():

hobbies = data.getlist('hobbies')

Uploaded files aren't part of the data, but access through FILES:

portrait_file = request.FILES.get('portrait')
Strategy Guide Photo

Save Time With Django Strategy Guides

Save time in your Django development projects: download our free strategy guides on Django Filters and Django Tag Templates.