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

lists/forms.py.

class

ItemForm

(

forms

.

Form

):

item_text

=

forms

.

CharField

(

widget

=

forms

.

fields

.

TextInput

(

attrs

=

{

'placeholder'

:

'Enter a to-do item'

,

}),

)

That gives:

AssertionError: 'class="form-control input-lg"' not found in '<p><label

for="id_item_text">Item text:</label> <input id="id_item_text" name="item_text"

placeholder="Enter a to-do item" type="text" /></p>'

And then:

lists/forms.py.

widget

=

forms

.

fields

.

TextInput

(

attrs

=

{

'placeholder'

:

'Enter a to-do item'

,

'class'

:

'form-control input-lg'

,

}),

Doing this sort of widget customisation would get tedious if we had

a much larger, more complex form. Check out

django-crispy-forms

and

django-floppyforms

for some help.

Development-Driven Tests: Using Unit Tests for Exploratory Coding

Does this feel a bit like development-driven tests? That’s OK, now and again.

When you’re exploring a new API, you’re absolutely allowed to mess about with it for

a while before you get back to rigorous TDD. You might use the interactive console, or

write some exploratory code (but you have to promise the Testing Goat that you’ll throw

it away and rewrite it properly later).

Here we’re actually using a unit test as a way of experimenting with the forms API. It’s

actually a pretty good way of learning how it works.

Switching to a Django ModelForm

What’s next? We want our form to reuse the validation code that we’ve already defined

on our model. Django provides a special class which can auto-generate a form for a

model, called

ModelForm

. As you’ll see, it’s configured using a special attribute called

Meta

:

lists/forms.py.

from

django

import

forms

Moving Validation Logic into a Form

|

195