Background Image
Table of Contents Table of Contents
Previous Page  221 / 478 Next Page
Information
Show Menu
Previous Page 221 / 478 Next Page
Page Background

CHAPTER 11

A Simple Form

At the end of the last chapter, we were left with the thought that there was too much

duplication of code in the validation handling bits of our views. Django encourages you

to use form classes to do the work of validating user input, and choosing what error

messages to display. Let’s see how that works.

As we go through the chapter, we’ll also spend a bit of time tidying up our unit tests,

and making sure each of them only tests one thing at a time.

Moving Validation Logic into a Form

In Django, a complex view is a code smell. Could some of that logic

be pushed out to a form? Or to some custom methods on the mod‐

el class? Or maybe even to a non-Django module that represents your

business logic?

Forms have several superpowers in Django:

• They can process user input and validate it for errors.

• They can be used in templates to render HTML input elements, and error messages

too.

• And, as we’ll see later, some of them can even save data to the database for you.

You don’t have to use all three form superpowers in every form. You may prefer to roll

your own HTML, or do your own saving. But they are an excellent place to keep vali‐

dation logic.

193