Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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:

  1. 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)
    
  2. 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)
    
  3. Save views.py.
  4. Open a command prompt and navigate to the chapter4 directory:
    $ cd django-1.1\django\bin\chapter4
  5. Run the development server:
    $ python manage.py runserver
  6. Navigate your browser to http://localhost:8000.

    You should see the Web page shown in Figure 4.6.

    Figure 4.6

    Figure 4.6 Displaying all a user's favorites.

  • + Share This
  • 🔖 Save To Your Account