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

Displaying Data from the View

The previous task displayed a placeholder Web page, but no actual data. We need some way to display data in our Web pages, because the goal of this chapter is to fetch data from the model and display it.

Django provides a special syntax you can use to insert data into your Django Web pages in the view, and you'll see how that works in this task.

Here, we'll insert the text string "Here is the text!" into the Web page to see how inserting data from a view works.

To display data from the view:

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

    Listing 4.7. 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>
            %s
          </body>
        </html>''' % (
            .
            .
            .
        )
      return HttpResponse(output)
    
    This code lets you include a list of data values in the parentheses after the % character that will be inserted into the earlier text. In this case, we're indicating that we're going to list one text string that should be inserted at the location of the %s code.
  2. Add the 'Here is the text!' text string that will be inserted into the Web page at the location of the %s code (Listing 4.8).

    Listing 4.8. The completed 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>
            %s
          </body>
        </html>''' % (
           'Here is the text!'
        )
      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.2.

    Figure 4.2

    Figure 4.2 Displaying data inserted into a Web page.

Now you know how to insert data into a Web page created in the view. The next step is to fetch some data from the model and display it in the Web page, which we'll do in the following task.

  • + Share This
  • 🔖 Save To Your Account