![Show Menu](styles/mobile-menu.png)
![Page Background](./../common/page-substrates/page0236.jpg)
that’s quite involved…this is the kind of thing that, without tests, would seriously worry
me. In fact, I might well have decided that it wasn’t worth messing with code that works
… but, because we have a full tests suite, we can delve around in it, tidying things up,
safe in the knowledge that the tests are there to spot any mistakes we make. It just makes
it that much likelier that you’re going to keep refactoring, keep tidying up, keep gar‐
dening, keep tending your code, keep everything neat and tidy and clean and smooth
and precise and concise and functional and good.
•
Remove duplication of validation logic in
views
Definitely time for a commit:
$
git diff
$
git commit -am"use form in all views, back to working state"
Using the Form’s Own Save Method
There are a couple more things we can do to make our views even simpler. I’ve men‐
tioned that forms are supposed to be able to save data to the database for us. Our case
won’t quite work out of the box, because the item needs to know what list to save to, but
it’s not hard to fix that.
We start, as always, with a test. Just to illustratewhat the problemis, let’s seewhat happens
if we just try to call
form.save()
:
lists/tests/test_forms.py (ch11l032).
def
test_form_save_handles_saving_to_a_list
(
self
):
form
=
ItemForm
(
data
=
{
'text'
:
'do me'
})
new_item
=
form
.
save
()
Django isn’t happy, because an item needs to belong to a list:
django.db.utils.IntegrityError: NOT NULL constraint failed: lists_item.list_id
Our solution is to tell the form’s save method what list it should save to:
lists/tests/test_forms.py.
from
lists.models
import
Item
,
List
[
...
]
def
test_form_save_handles_saving_to_a_list
(
self
):
list_
=
List
.
objects
.
create
()
208
|
Chapter 11: A Simple Form