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 a Specific User's Favorite

In this task, we'll display the title of a user's favorite. We'll start by getting an object corresponding to the user (change the name of the user as appropriate to match your database):

  user = User.objects.
    get(username='steve')

Then, to find the title of the favorite, just pass the get method the User object to get the user's favorite, and use the title field to find the favorite's title:

  user = User.objects.
     get(username='steve')

  title = Favorite.objects.
    get(user=user).title

To access a specific user’s favorite:

  1. Using a text editor, edit chapter4\favorites\views.py, adding the code shown in Listing 4.13.

    Listing 4.13. 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):
      output = '''
        <html>
          <head>
            <title>
              Connecting to the model
            </title>
          </head>
          <body>
            <h1>
              Connecting to the model
            </h1>
            Title of steve's favorite: %s
          </body>
        </html>''' % (
            .
            .
            .
        )
      return HttpResponse(output)
    
  2. Add the code to actually access the title of the user's favorite and display it, shown in Listing 4.14.

    Listing 4.14. 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')
      title = Favorite.objects.get(user=user)
    title
      output = '''
        <html>
          <head>
            <title>
              Connecting to the model
            </title>
          </head>
          <body>
            <h1>
              Connecting to the model
            </h1>
            Title of steve's favorite: %s
          </body>
        </html>''' % (
           title
        )
      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.5.

    Figure 4.5

    Figure 4.5 Displaying a user's favorite.

  • + Share This
  • 🔖 Save To Your Account