Accessing All Favorites for a User
Given a User object, you can find all the favorites of that user by using the expression user.favorite_set.all( ).
When you get all the favorites of a user, you can loop over them, displaying all their titles like this:
from favorites.models import * def main_page(request): user = User.objects. get(username='steve') favorites = user.favorite_set.all( ) list = '' for favorite in favorites: list = list + favorite.title + ' <br> '
We'll now find the titles of all the favorites of a particular user.
To find all favorites of a particular user:
- Using a text editor, edit chapter4\favorites\views.py, adding the code shown in Listing 4.15.
Listing 4.15. The edited views.py file.
from django.http import HttpResponse from django.contrib.auth.models import User from favorites.models import * def main_page(request): user = User.objects.get(username='steve') output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> All of steve's favorites: %s </body> </html>''' % ( . . . ) return HttpResponse(output)
- Add the code to actually access all the user's favorites and display them, shown in Listing 4.16.
Listing 4.16. The completed views.py file.
from django.http import HttpResponse from django.contrib.auth.models import User from favorites.models import * def main_page(request): user = User.objects.get(username='steve') favorites = user.favorite_set.all( ) list = '' for favorite in favorites: list = list + favorite.title + ' <br> ' output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> All of steve's favorites: %s </body> </html>''' % ( list ) return HttpResponse(output)
- Save views.py.
- Open a command prompt and navigate to the chapter4 directory:
$ cd django-1.1\django\bin\chapter4
- Run the development server:
$ python manage.py runserver
- Navigate your browser to http://localhost:8000.
You should see the Web page shown in Figure 4.6.
Figure 4.6 Displaying all a user's favorites.