![Show Menu](styles/mobile-menu.png)
![Page Background](./../common/page-substrates/page0226.png)
'text'
: {
'required'
:
EMPTY_LIST_ERROR
}
}
Rerun the tests to see they pass … OK. Now we change the test:
lists/tests/test_forms.py (ch11l012).
from
lists.forms
import
EMPTY_LIST_ERROR
,
ItemForm
[
...
]
def
test_form_validation_for_blank_items
(
self
):
form
=
ItemForm
(
data
=
{
'text'
:
''
})
self
.
assertFalse
(
form
.
is_valid
())
self
.
assertEqual
(
form
.
errors
[
'text'
], [
EMPTY_LIST_ERROR
])
And the tests still pass:
OK
Great. Totes committable:
$
git status
# should show lists/forms.py and tests/test_forms.py
$
git add lists
$
git commit -m "new form for list items"
Using the Form in Our Views
I had originally thought to extend this form to capture uniqueness validation as well as
empty-item validation. But there’s a sort of corollary to the “deploy as early as possible”
lean methodology, which is “merge code as early as possible”. In other words: while
building this bit of forms code, it would be easy to go on for ages, adding more and
more functionality to the form—I should know, because that’s exactly what I did during
the drafting of this chapter, and I ended up doing all sorts of workmaking an all-singing,
all-dancing form class before I realised it wouldn’t really work for our most basic use
case.
So, instead, try and use your new bit of code as soon as possible. This makes sure you
never have unused bits of code lying around, and that you start checking your code
against “the real world” as soon as possible.
We have a form class which can render some HTML and do validation of at least one
kind of error—let’s start using it! We should be able to use it in our
base.html
template,
and so in all of our views.
Using the Form in a View with a GET Request
Let’s start in our unit tests for the home view. We’ll replace the old-style
test_home_page_returns_correct_html
and
test_root_url_resolves_to_home_
page_view
with a set of tests that use the Django test client. We leave the old tests in at
first, to check that our new tests are equivalent:
198
|
Chapter 11: A Simple Form