Creating the View
The next task in getting our favorites application running is to create the view. That involves two steps: first, we have to write views.py, and second, we have to tell Django about the view we've set up by editing urls.py.
To create the view:
- Using a text editor, edit chapter4\favorites\views.py to add a new view named main_page, replacing the current version of views.py with the code in Listing 4.5.
Listing 4.5. The edited views.py file.
from django.http import HttpResponse def main_page(request): output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> We will use this application to connect to the model. </body> </html>''' return HttpResponse(output)
- Save views.py.
- Edit chapter4\urls.py to add the main_page view to the application, making the additions shown in Listing 4.6.
Listing 4.6. The edited urls.py file.
from django.conf.urls.defaults import * from favorites.views import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover( ) urlpatterns = patterns('', (r'^$', main_page), )
- Save urls.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.1.
Figure 4.1 Starting our favorites application.