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

ValueError: Cannot assign "<SimpleLazyObject:

<django.contrib.auth.models.AnonymousUser object at 0x7f364795ef90>>":

"List.owner" must be a "User" instance.

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

[...]

ValueError: Cannot assign "<SimpleLazyObject:

<django.contrib.auth.models.AnonymousUser object at 0x7f364795ef90>>":

"List.owner" must be a "User" instance.

We’re moving back up to the views layer now, just doing a little tidying up. Notice that

these are in the old test for the

new_list

view, when we haven’t got a logged-in user. We

should only save the list owner when the user is actually logged in. The

.is_authenti

cated()

function we defined in

Chapter 16

comes in useful now (when they’re not

logged in, Django represents users using a class called

AnonymousUser

, whose

.is_au

thenticated()

always returns

False

):

lists/views.py (ch18l023).

if

form

.

is_valid

():

list_

=

List

()

if

request

.

user

.

is_authenticated

():

list_

.

owner

=

request

.

user

list_

.

save

()

form

.

save

(

for_list

=

list_

)

[

...

]

And that gets us passing!

$

python3 manage.py test lists

Creating test database for alias 'default'...

.......................................

---------------------------------------------------------------------

Ran 39 tests in 0.237s

OK

Destroying test database for alias 'default'...

This is a good time for a commit:

$

git add lists

$

git commit -m"lists can have owners, which are saved on creation."

Final Step: Feeding Through the .name API from the Template

The last thing our outside-in design wanted came from the templates, which wanted to

be able to access a list “name” based on the text of its first item:

lists/tests/test_models.py (ch18l024).

def

test_list_name_is_first_item_text

(

self

):

list_

=

List

.

objects

.

create

()

Item

.

objects

.

create

(

list

=

list_

,

text

=

'first item'

)

Item

.

objects

.

create

(

list

=

list_

,

text

=

'second item'

)

self

.

assertEqual

(

list_

.

name

,

'first item'

)

Moving Down to the Model Layer

|

333