Background Image
Table of Contents Table of Contents
Previous Page  443 / 478 Next Page
Information
Show Menu
Previous Page 443 / 478 Next Page
Page Background

Using form_valid to Customise a CreateView

Next we have a crack at the viewwe use to create a brand new list, currently the

new_list

function. Here’s what it looks like now:

lists/views.py.

def

new_list

(

request

):

form

=

ItemForm

(

data

=

request

.

POST

)

if

form

.

is_valid

():

list

=

List

.

objects

.

create

()

form

.

save

(

for_list

=

list_

)

return

redirect

(

list_

)

else

:

return

render

(

request

,

'home.html'

, {

"form"

:

form

})

Looking through the possible CBGVs, we probably want a

CreateView

, and we know

we’re using the

ItemForm

class, so let’s see how we get on with them, and whether the

tests will help us:

lists/views.py (ch31l003).

from

django.views.generic

import

FormView

,

CreateView

[

...

]

class

NewListView

(

CreateView

):

form_class

=

ItemForm

def

new_list

(

request

):

[

...

]

I’m going to leave the old view function in

views.py

, so that we can copy code across

from it. We can delete it once everything is working. It’s harmless as soon as we switch

over the URL mappings, this time in:

lists/urls.py (ch31l004).

from

django.conf.urls

import

patterns

,

url

from

lists.views

import

NewListView

urlpatterns

=

patterns

(

''

,

url

(

r'^(\d+)/$'

,

'lists.views.view_list'

,

name

=

'view_list'

),

url

(

r'^new$'

,

NewListView

.

as_view

(),

name

=

'new_list'

),

)

Now running the tests gives three errors:

$

python3 manage.py test lists

ERROR: test_for_invalid_input_passes_form_to_template

(lists.tests.test_views.NewListTest)

django.core.exceptions.ImproperlyConfigured: TemplateResponseMixin requires

either a definition of 'template_name' or an implementation of

'get_template_names()'

ERROR: test_for_invalid_input_renders_home_template (lists.tests.test_views.NewListTest)

django.core.exceptions.ImproperlyConfigured: TemplateResponseMixin requires

either a definition of 'template_name' or an implementation of

Using form_valid to Customise a CreateView

|

415