![Show Menu](styles/mobile-menu.png)
![Page Background](./../common/page-substrates/page0442.png)
find that using class-based views can (again, debatably) lead to code that’s much harder
to read than a classic view function.
Still, because we’re forced to use several of the customisation options for class-based
views, implementing them in this case can teach us a lot about how they work, and how
we can unit test them.
My hope is that the same unit tests we use for function-based views should work just as
well for class-based views. Let’s see how we get on.
The Home Page as a FormView
Our home page just displays a form on a template:
def
home_page
(
request
):
return
render
(
request
,
'home.html'
, {
'form'
:
ItemForm
()})
Looking through the options ,Django has a generic view called
FormView
—let’s see how
that goes:
lists/views.py (ch31l001).
from
django.views.generic
import
FormView
[
...
]
class
HomePageView
(
FormView
):
template_name
=
'home.html'
form_class
=
ItemForm
We tell it what template we want to use, and which form. Then, we just need to update
urls.py
, replacing the line that used to say
lists.views.home_page
:
superlists/urls.py (ch31l002).
url
(
r'^$'
,
HomePageView
.
as_view
(),
name
=
'home'
),
And the tests all check out! That was easy…
$
python3 manage.py test lists
[...]
Ran 34 tests in 0.119s
OK
$
python3 manage.py test functional_tests
[...]
Ran 4 tests in 15.160s
OK
So far so good. We’ve replaced a one-line view function with a two-line class, but it’s still
very readable. This would be a good time for a commit…
414
|
Appendix B: Django Class-Based Views