![Show Menu](styles/mobile-menu.png)
![Page Background](./../common/page-substrates/page0250.png)
AssertionError: <lists.forms.ItemForm object at 0x7f767e4b7f90> is not an
instance of <class 'lists.forms.ExistingListItemForm'>
So we can adjust the view:
lists/views.py (ch12l051).
from
lists.forms
import
ExistingListItemForm
,
ItemForm
[
...
]
def
view_list
(
request
,
list_id
):
list_
=
List
.
objects
.
get
(
id
=
list_id
)
form
=
ExistingListItemForm
(
for_list
=
list_
)
if
request
.
method
==
'POST'
:
form
=
ExistingListItemForm
(
for_list
=
list_
,
data
=
request
.
POST
)
if
form
.
is_valid
():
form
.
save
()
[
...
]
And that
almost
fixes everything, except for an unexpected fail:
TypeError: save() missing 1 required positional argument: 'for_list'
Our custom save method from the parent
ItemForm
is no longer needed. Let’s make a
quick unit test for that:
lists/tests/test_forms.py (ch12l053).
def
test_form_save
(
self
):
list_
=
List
.
objects
.
create
()
form
=
ExistingListItemForm
(
for_list
=
list_
,
data
=
{
'text'
:
'hi'
})
new_item
=
form
.
save
()
self
.
assertEqual
(
new_item
,
Item
.
objects
.
all
()[
0
])
We can make our form call the grandparent save method:
lists/forms.py (ch12l054).
def
save
(
self
):
return
forms
.
models
.
ModelForm
.
save
(
self
)
Personal opinion here: I could have used
super
, but I prefer not to
use
super
when it requires arguments, eg to get a grandparent meth‐
od. I find Python 3’s
super()
with no args awesome to get the im‐
mediate parent. Anything else is too error-prone, and I find it ugly
besides. YMMV.
And we’re there! All the unit tests pass:
$
python3 manage.py test lists
[...]
Ran 34 tests in 0.082s
OK
And so does our FT for validation:
$
python3 manage.py test functional_tests.test_list_item_validation
Creating test database for alias 'default'...
222
|
Chapter 12: More Advanced Forms