Your First View: Dynamic Content

As our first goal, let’s create a Web page that displays the current date and time. This is a good example of a dynamic Web page, because the contents of the page are not static—rather, the contents change according to the result of a computation (in this case, a calculation of the current time). This simple example doesn’t involve a database or any sort of user input—just the output of your server’s internal clock.

To create this page, we’ll write a view function. A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image … or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement—no “magic,” so to speak. For the sake of putting the code somewhere, let’s create a file called views.py in the mysite directory, which you created in the previous chapter. Here’s a view that returns the current date and time, as an HTML document:

from django.http import HttpResponse

import datetime

def current_datetime(request):  

    now = datetime.datetime.now()    

    html = "<html><body>It is now %s.</body></html>" % now    

    return HttpResponse(html)


Let’s step through this code one line at a time:

  • First, we import the class HttpResponse, which lives in the django.http module.
  • Then we import the datetime module from Python’s standard library, the set of useful modules that comes with Python. The datetime module contains several functions and classes for dealing with dates and times, including a function that returns the current time.
  • Next, we define a function called current_datetime. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request.
  • Note that the name of the view function doesn’t matter; it doesn’t have to be named in a certain way in order for Django to recognize it. We’re calling it current_datetime here, because that name clearly indicates what it does, but it could just as well be named super_duper_awesome_current_time, or something equally revolting. Django doesn’t care. The next section explains how Django finds this function.
  • The first line of code within the function calculates the current date/time, as a datetime.datetime object, and stores that as the local variable now.
  • The second line of code within the function constructs an HTML response using Python’s format-string capability. The %s within the string is a placeholder, and the percent sign after the string means “Replace the %s with the value of the variable now.” (Yes, the HTML is invalid, but we’re trying to keep the example simple and short.)
  • Finally, the view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object. (There are exceptions, but we’ll get to those later.)

Django’s Time Zone – Django includes a TIME_ZONE setting that defaults to America/Chicago. This probably isn’t where you live, so you might want to change it in your settings.py.

As our first goal, let’s create a web page that outputs that famous example message: “Hello world.” If you were publishing a simple “Hello world” web page without a web framework, you’d simply type “Hello world” into a text file, call it “hello.html“, and upload it to a directory on a web server somewhere. Notice in that process you’ve specified two key pieces of information about that web page: its contents (the string “Hello world”) and its URL (e.g. http://www.example.com/hello.html).

Your First View

With Django, you specify those same two things, but in a different way. The contents of the page are produced by a view function, and the URL is specified in a URLconf. First, let’s write our “Hello world” view function.

Within the inner mysite directory that we created in the last chapter, create an empty file called views.py. This Python module will contain our views for this chapter. Make sure you put the file in the inner mysite directory, i.e. the \mysite\mysite\ directory, not the directory containing manage.py.

Our “Hello world” view is simple. Here’s the entire function, plus import statements, which you should type into the views.py file:

from django.http import HttpResponsedef hello(request):    return HttpResponse("Hello world")

Let’s step through this code one line at a time:

  • First, we import the class HttpResponse, which lives in the django.http module. We need to import this class because it’s used later in our code.
  • Next, we define a function called hello – the view function.
  • Each view function takes at least one parameter, called request by convention. This is an object that contains information about the current web request that has triggered this view, and is an instance of the class django.http.HttpRequest.

In this example, we don’t do anything with request, but it must be the first parameter of the view nonetheless. Note that the name of the view function doesn’t matter; it doesn’t have to be named in a certain way in order for Django to recognize it. We’re calling it hello here, because that name clearly indicates the gist of the view, but it could just as well be named hello_wonderful_beautiful_world, or something equally revolting.

The next section, “Your First URLconf”, will shed light on how Django finds this function. The function is a simple one-liner: it merely returns an HttpResponse object that has been instantiated with the text “Hello world”. The main lesson here is this: a view is just a Python function that takes an HttpRequest as its first parameter and returns an instance of HttpResponse. In order for a Python function to be a Django view, it must do these two things. (There are exceptions, but we’ll get to those later.)

Back Tutorial

The Basics of Dynamic Web Pages
Mapping URLs to Views

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?