Accessing the First Favorite from the Model
In this task, we'll begin accessing data from the model using code in the view. In particular, we'll access the first Favorite object, created in Chapter 3, and display its title in a Web page.
To do that, we have to make the code in the view aware of the model, and you do that by importing all the models from favorites.models (the compiled models.py) in views.py:
from favorites.models import *
Accessing the model in code works much as it did in the shell in Chapter 3. For example, to access the Favorite objects in the model, you use this syntax:
Favorite.objects
To get the first Favorite object, use the get method, getting the Favorite object with the ID of 1:
Favorite.objects.get(id=1)
Then to access the Favorite object's title field, use this syntax:
Favoite.objects.get(id=1).title
And that's how we'll access the title of the first favorite Web site in the database (you may recall from Chapter 3 that the title of the first favorite was USA Today).
To access the first favorite from the model:
- Using a text editor, edit chapter4\favorites\views.py, adding the code shown in Listing 4.9.
Listing 4.9. The edited views.py file.
from django.http import HttpResponse 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> Here's the title of the first favorite: %s </body> </html>''' % ( . . . ) return HttpResponse(output)
- Add the code to actually access the title of the first favorite and display it, shown in Listing 4.10.
Listing 4.10. The completed views.py file.
from django.http import HttpResponse from favorites.models import * def main_page(request): title = Favorite.objects.get(id=1).title output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> Here's the title of the first favorite: %s </body> </html>''' % ( title ) 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.3.
Figure 4.3 Displaying the title of the first favorite.