And the
KeyError: 'form'
was still there too!
At this point the errors stopped being quite as helpful, and it was no longer obvious
what to do next. I had to resort to trial and error. Still, the tests did at least tell me when
I was getting things more right or more wrong.
My first attempts to use
get_form_kwargs
didn’t really work, but I found that I could
use
get_form
:
lists/views.py.
def
get_form
(
self
,
form_class
):
self
.
object
=
self
.
get_object
()
return
form_class
(
for_list
=
self
.
object
,
data
=
self
.
request
.
POST
)
But it would only work if I also assigned to
self.object
, as a side effect, along the way,
which was a bit upsetting. Still, that takes us down to just three errors, but we’re still
apparently not passing that form to the template!
KeyError: 'form'
FAILED (errors=3)
Back on Track
A bit more experimenting led me to swap out the
DetailView
for a
SingleObjectMix
in
(the docs had some useful pointers here):
from django.views.generic.detail import SingleObjectMixin
[...]
class ViewAndAddToList(CreateView, SingleObjectMixin):
[...]
That takes us down to just two errors:
django.core.exceptions.ImproperlyConfigured: No URL to redirect to. Either
provide a url or define a get_absolute_url method on the Model.
And for this final failure, the tests are being helpful again. It’s quite easy to define a
get_absolute_url
on the
Item
class, such that items point to their parent list’s page:
lists/models.py.
class
Item
(
models
.
Model
):
[
...
]
def
get_absolute_url
(
self
):
return
reverse
(
'view_list'
,
args
=
[
self
.
list
.
id
])
A More Complex View to Handle Both Viewing and Adding to a List
|
419