ModelForm and Validation

What a form does. It takes untrusted input, checks it, converts it to proper Python types, and hands back either clean data or a set of errors. A ModelForm derives all of that from a model you already wrote.

List your fields explicitly. fields = "__all__" is convenient and will cheerfully expose a column you never meant anyone to set. Naming them is one extra line and it is the line that stops a person editing published or author by adding a field to the submitted form.

This is not hypothetical. Anything not in the form cannot be set by the request, and anything in it can.

Where custom validation goes.

clean_<fieldname> validates one field and returns its cleaned value.

clean() validates the form as a whole, for rules involving more than one field.

After validation, read form.cleaned_data, never request.POST. The cleaned version has been checked and converted; the raw version is whatever was sent.

◈ Graded Challenge

Write validate(data) modeling a form's clean step. data is a dictionary of submitted strings. Return a dictionary with two keys: "errors", a dictionary mapping field names to messages, and "cleaned", a dictionary of usable values that is empty when there are any errors. Rules: title is required and must be at least 3 characters after stripping surrounding whitespace, giving "required" when missing or empty and "too short" when it is 1 or 2 characters. body is required, giving "required". published must be the string "on" or absent, and becomes a real boolean in cleaned. On success, cleaned holds the stripped title, the body unchanged, and published as a boolean.

Name it exactly: validate(data)

Python4 visible + 5 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Rendering and CSRF →
← Back