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

self

.

instance

.

validate_unique

()

except

ValidationError

as

e

:

e

.

error_dict

=

{

'text'

: [

DUPLICATE_ITEM_ERROR

]}

self

.

_update_errors

(

e

)

That’s a bit of Django voodoo right there, but we basically take the validation error,

adjust its error message, and then pass it back into the form. And we’re there! A quick

commit:

$

git diff

$

git commit -a

Using the Existing List Item Form in the List View

Now let’s see if we can put this form to work in our view.

We remove the skip, and while we’re at it, we can use our new constant. Tidy.

lists/tests/test_views.py (ch12l049).

from

lists.forms

import

(

DUPLICATE_ITEM_ERROR

,

EMPTY_LIST_ERROR

,

ExistingListItemForm

,

ItemForm

,

)

[

...

]

def

test_duplicate_item_validation_errors_end_up_on_lists_page

(

self

):

[

...

]

expected_error

=

escape

(

DUPLICATE_ITEM_ERROR

)

That brings back out integrity error:

django.db.utils.IntegrityError: UNIQUE constraint failed: lists_item.list_id,

lists_item.text

Our fix for this is to switch to using the new form class. Before we implement it, let’s

find the tests where we check the form class, and adjust them:

lists/tests/test_views.py (ch12l050).

class

ListViewTest

(

TestCase

):

[

...

]

def

test_displays_item_form

(

self

):

list_

=

List

.

objects

.

create

()

response

=

self

.

client

.

get

(

'/lists/

%d

/'

%

(

list_

.

id

,))

self

.

assertIsInstance

(

response

.

context

[

'form'

],

ExistingListItemForm

)

self

.

assertContains

(

response

,

'name="text"'

)

[

...

]

def

test_for_invalid_input_passes_form_to_template

(

self

):

response

=

self

.

post_invalid_input

()

self

.

assertIsInstance

(

response

.

context

[

'form'

],

ExistingListItemForm

)

That gives us:

Using the Existing List Item Form in the List View

|

221