lists/views.py (ch31l007).
class
NewListView
(
CreateView
,
HomePageView
):
def
form_valid
(
self
,
form
):
list
=
List
.
objects
.
create
()
Item
.
objects
.
create
(
text
=
form
.
cleaned_data
[
'text'
],
list
=
list
)
return
redirect
(
'/lists/
%d
/'
%
(
list
.
id
,))
And all the tests would still pass:
OK
This is not really good object-oriented practice. Inheritance im‐
plies an “is-a” relationship, and it’s probably not meaningful to say
that our new list view “is-a” home page view… so, probably best not
to do this.
With or without that last step, how does it compare to the old version? I’d say that’s not
bad. We save some boilerplate code, and the view is still fairly legible. So far, I’d say we’ve
got one point for CBGVs, and one draw.
A More Complex View to Handle Both Viewing and Adding
to a List
This took me
several
attempts. And I have to say that, although the tests told me when
I got it right, they didn’t really help me to figure out the steps to get there … mostly it
was just trial and error, hacking about in functions like
get_context_data
,
get_form_kwargs
, and so on.
One thing it did made me realise was the value of having lots of individual tests, each
testing one thing. I went back and rewrote some of Chapters 10–12 as a result.
The Tests Guide Us, for a While
Here’s how things might go. Start by thinking we want a
DetailView
, something that
shows you the detail of an object:
lists/views.py.
from
django.views.generic
import
FormView
,
CreateView
,
DetailView
[
...
]
class
ViewAndAddToList
(
DetailView
):
model
=
List
That gives:
[...]
AttributeError: Generic detail view ViewAndAddToList must be called with either
an object pk or a slug.
A More Complex View to Handle Both Viewing and Adding to a List
|
417