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

Good, the form won’t allow you to save if you give it an empty item text.

Now let’s see if we can get it to use the specific error message that we want. The API for

checking form validation

before

we try and save any data is a function called

is_valid

:

lists/tests/test_forms.py (ch11l009).

def

test_form_validation_for_blank_items

(

self

):

form

=

ItemForm

(

data

=

{

'text'

:

''

})

self

.

assertFalse

(

form

.

is_valid

())

self

.

assertEqual

(

form

.

errors

[

'text'

],

[

"You can't have an empty list item"

]

)

Calling

form.is_valid()

returns

True

or

False

, but it also has the side effect of vali‐

dating the input data, and populating the

errors

attribute. It’s a dictionary mapping the

names of fields to lists of errors for those fields (it’s possible for a field to have more than

one error).

That gives us:

AssertionError: ['This field is required.'] != ["You can't have an empty list

item"]

Django already has a default error message that we could present to the user—youmight

use it if you were in a hurry to build your web app, but we care enough to make our

message special. Customising it means changing

error_messages

, another

Meta

variable:

lists/forms.py (ch11l010).

class

Meta

:

model

=

Item

fields

=

(

'text'

,)

widgets

=

{

'text'

:

forms

.

fields

.

TextInput

(

attrs

=

{

'placeholder'

:

'Enter a to-do item'

,

'class'

:

'form-control input-lg'

,

}),

}

error_messages

=

{

'text'

: {

'required'

:

"You can't have an empty list item"

}

}

OK

You know what would be even better than messing about with all these error strings?

Having a constant:

lists/forms.py (ch11l011).

EMPTY_LIST_ERROR

=

"You can't have an empty list item"

[

...

]

error_messages

=

{

Moving Validation Logic into a Form

|

197