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

expected_error

=

escape

(

"You've already got this in your list"

)

self

.

assertContains

(

response

,

expected_error

)

self

.

assertTemplateUsed

(

response

,

'list.html'

)

self

.

assertEqual

(

Item

.

objects

.

all

()

.

count

(),

1

)

Gives:

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

lists_item.text

We want to avoid integrity errors! Ideally, we want the call to

is_valid

to somehow

notice the duplication error before we even try to save, but to do that, our form will

need to know what list it’s being used for, in advance.

Let’s put a skip on that test for now:

lists/tests/test_views.py (ch12l015).

from

unittest

import

skip

[

...

]

@skip

def

test_duplicate_item_validation_errors_end_up_on_lists_page

(

self

):

A More Complex Form to Handle Uniqueness Validation

The form to create a new list only needs to know one thing, the new item text. A form

which validates that list items are unique needs to know both. Just like we overrode the

save method on our

ItemForm

, this time we’ll override the constructor on our new form

class so that it knows what list it applies to.

We duplicate our tests for the previous form, tweaking them slightly:

lists/tests/test_forms.py (ch12l016).

from

lists.forms

import

(

DUPLICATE_ITEM_ERROR

,

EMPTY_LIST_ERROR

,

ExistingListItemForm

,

ItemForm

)

[

...

]

class

ExistingListItemFormTest

(

TestCase

):

def

test_form_renders_item_text_input

(

self

):

list_

=

List

.

objects

.

create

()

form

=

ExistingListItemForm

(

for_list

=

list_

)

self

.

assertIn

(

'placeholder="Enter a to-do item"'

,

form

.

as_p

())

def

test_form_validation_for_blank_items

(

self

):

list_

=

List

.

objects

.

create

()

form

=

ExistingListItemForm

(

for_list

=

list_

,

data

=

{

'text'

:

''

})

self

.

assertFalse

(

form

.

is_valid

())

self

.

assertEqual

(

form

.

errors

[

'text'

], [

EMPTY_LIST_ERROR

])

A More Complex Form to Handle Uniqueness Validation

|

219