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

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:

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

    You should see the Web page shown in Figure 4.1.

    Figure 4.1

    Figure 4.1 Starting our favorites application.

  • + Share This
  • 🔖 Save To Your Account