Django Views: Dynamic Content

Your Second View: Dynamic Content

The “Hello world” view was instructive in demonstrating the basics of how Django works, but it wasn’t an example of a dynamic web page, because the content of the page is always the same. Every time you view /hello/, you’ll see the same thing; it might as well be a static HTML file.

For our second view, let’s create something more dynamic – a web page that displays the current date and time. This is a nice, simple next step, because it doesn’t involve a database or any user input – just the output of your server’s internal clock. It’s only marginally more exciting than “Hello world,” but it’ll demonstrate a few new concepts.

This new view needs to do two things: calculate the current date and time, and return an HttpResponse containing that value. If you have experience with Python, you know that Python includes a datetime module for calculating dates. Here’s a demonstration using the Python interactive interpreter:

C:\Users\nigel>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2017, 5, 20, 14, 32, 25, 412665)
>>> print (now)
2017-05-20 14:32:25.412665
>>>

That’s simple enough, and it has nothing to do with Django. It’s just Python code. (I want to emphasize that you should be aware of what code is “just Python” vs. code that is Django-specific. As you learn Django, I want you to be able to apply your knowledge to other Python projects that don’t necessarily use Django.)

To make a Django view that displays the current date and time, we just need to hook this datetime.datetime.now() statement into a view and return an HttpResponse. Here’s what the updated views.py looks like:

from django.http import HttpResponse
import datetime

def hello(request):
    return HttpResponse("Hello world")

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 the changes we’ve made to views.py to accommodate the current_datetime view.

  • We’ve added an import datetime to the top of the module, so we can calculate dates.
  • The new current_datetime function calculates the current date and time, as a datetime.datetime object, and stores that as the local variable now.
  • The second line of code within the view 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 in the preceding string with the value of the variable now.” The now variable is technically a datetime.datetime object, not a string, but the %s format character converts it to its string representation, which is something like “2017-05-20 14:32:25.412665“. This will result in an HTML string such as “It is now 2017-05-20 14:32:25.412665.“.
  • Finally, the view returns an HttpResponse object that contains the generated response – just as we did in hello.

After adding that to views.py, add the URLpattern to urls.py to tell Django which URL should handle this view. Something like /time/ would make sense:

from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello, current_datetime

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
    url(r'^time/$', current_datetime),
]

We’ve made two changes here. First, we imported the current_datetime function at the top. Second, and more importantly, we added a URLpattern mapping the URL /time/ to that new view. Getting the hang of this? With the view written and URLconf updated, fire up the development server and visit http://127.0.0.1:8000/time/ in your browser. You should see the current date and time.

URLconfs and Loose Coupling

Now’s a good time to highlight a key philosophy behind URLconfs and behind Django in general: the principle of loose coupling. Simply put, loose coupling is a software-development approach that values the importance of making pieces interchangeable. If two pieces of code are loosely coupled, then changes made to one of the pieces will have little or no effect on the other.

Django’s URLconfs are a good example of this principle in practice. In a Django web application, the URL definitions and the view functions they call are loosely coupled – i.e., the decision of what the URL should be for a given function, and the implementation of the function itself, reside in two separate places.

For example, consider our current_datetime view. If we wanted to change the URL for the application – say, to move it from /time/ to /current-time/– we could make a quick change to the URLconf, without having to worry about the view itself. Similarly, if we wanted to change the view function – altering its logic somehow – we could do that without affecting the URL to which the function is bound. Furthermore, if we wanted to expose the current-date functionality at several URLs, we could easily take care of that by editing the URLconf, without having to touch the view code.

In this example, our current_datetime is available at two URLs. It’s a contrived example, but this technique can come in handy:

urlpatterns = [
      url(r'^admin/', admin.site.urls),
      url(r'^hello/$', hello),
      url(r'^time/$', current_datetime),
      url(r'^another-time-page/$', current_datetime),
]

URLconfs and views are loose coupling in action. I’ll continue to point out examples of this important philosophy throughout the book.

Your Third View: Dynamic URLs

In our current_datetime view, the contents of the page – the current date/time – were dynamic, but the URL (/time/) was static. In most dynamic web applications though, a URL contains parameters that influence the output of the page. For example, an online bookstore might give each book its own URL, like /books/243/ and /books/81196/.

Let’s create a third view that displays the current date and time offset by a certain number of hours. The goal is to craft a site in such a way that the page /time/plus/1/ displays the date/time one hour into the future, the page /time/plus/2/ displays the date/time two hours into the future, the page /time/plus/3/ displays the date/time three hours into the future, and so on.

A novice might think to code a separate view function for each hour offset, which might result in a URLconf like this:

urlpatterns = [
    url(r'^time/$', current_datetime),
    url(r'^time/plus/1/$', one_hour_ahead),
    url(r'^time/plus/2/$', two_hours_ahead),
    url(r'^time/plus/3/$', three_hours_ahead),
]

Clearly, this line of thought is flawed.

Not only would this result in redundant view functions, but also the application is fundamentally limited to supporting only the predefined hour ranges – one, two or three hours.

If we decided to create a page that displayed the time four hours into the future, we’d have to create a separate view and URLconf line for that, furthering the duplication.

How, then do we design our application to handle arbitrary hour offsets? The key is to use wildcard URLpatterns. As I mentioned previously, a URLpattern is a regular expression; hence, we can use the regular expression pattern \d+ to match one or more digits:

urlpatterns = [
    # ...
    url(r'^time/plus/\d+/$', hours_ahead),
    # ...
]

(I’m using the # ... to imply there might be other URLpatterns that have been trimmed from this example.) This new URLpattern will match any URL such as /time/plus/2/, /time/plus/25/, or even /time/plus/100000000000/. Come to think of it, let’s limit it so that the maximum allowed offset is something reasonable.

In this example, we will set a maximum 99 hours by only allowing either one- or two-digit numbers – and in regular expression syntax, that translates into \d{1,2}:

url(r'^time/plus/\d{1,2}/$', hours_ahead),

Now that we’ve designated a wildcard for the URL, we need a way of passing that wildcard data to the view function, so that we can use a single view function for any arbitrary hour offset. We do this by placing parentheses around the data in the URLpattern that we want to save. In the case of our example, we want to save whatever number was entered in the URL, so let’s put parentheses around the \d{1,2},
like this:

url(r'^time/plus/(\d{1,2})/$', hours_ahead),

If you’re familiar with regular expressions, you’ll be right at home here; we’re using parentheses to capture data from the matched text. The final URLconf, including our previous two views, looks like this:

from django.conf.urls import include, url
from django.contrib import admin
from mysite.views import hello, current_datetime, hours_ahead

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
    url(r'^time/$', current_datetime),
    url(r'^time/plus/(\d{1,2})/$', hours_ahead),
]

With that taken care of, let’s write the hours_ahead view. hours_ahead is very similar to the current_datetime view we wrote earlier, with a key difference: it takes an extra argument, the number of hours of offset. Here’s the view code:

from django.http import Http404, HttpResponse
import datetime

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be  %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

Let’s take a closer look at this code.

The view function, hours_ahead, takes two parameters: request and offset:

  • request is an HttpRequest object, just as in hello and current_datetime. I’ll say it again: each view always takes an HttpRequest object as its first parameter.
  • offset is the string captured by the parentheses in the URLpattern. For example, if the requested URL were /time/plus/3/, then offset would be the string ‘3’. If the requested URL were /time/plus/21/, then offset would be the string ’21’. Note that captured values will always be Unicode objects, not integers, even if the string is composed of only digits, such as ’21’.

I decided to call the variable offset, but you can call it whatever you’d like, as long as it’s a valid Python identifier. The variable name doesn’t matter; all that matters is that it’s the second argument to the function, after request. (It’s also possible to use keyword, rather than positional, arguments in an URLconf. I cover that in Chapter 7.)

The first thing we do within the function is call int() on offset. This converts the Unicode string value to an integer.

Note that Python will raise a ValueError exception if you call int() on a value that cannot be converted to an integer, such as the string “foo”. In this example, if we encounter the ValueError, we raise the exception django.http.Http404, which, as you can imagine, results in a 404 “Page not found” error.

Astute readers will wonder: how could we ever reach the ValueError case, anyway, given that the regular expression in our URLpattern – (\d{1,2}) – captures only digits, and therefore offset will only ever be a string composed of digits? The answer is, we won’t, because the URLpattern provides a modest but useful level of input validation, but we still check for the ValueError in case this view function ever gets called in some other way. It’s good practice to implement view functions such that they don’t make any assumptions about their parameters. Loose coupling, remember?

In the next line of the function, we calculate the current date/time and add the appropriate number of hours. We’ve already seen datetime.datetime.now() from the current_datetime view; the new concept here is that you can perform date/time arithmetic by creating a datetime.timedelta object and adding to a datetime.datetime object. Our result is stored in the variable dt.

This line also shows why we called int() on offset – the datetime.timedelta function requires the hours parameter to be an integer.

Next, we construct the HTML output of this view function, just as we did in current_datetime. A small difference in this line from the previous line is that it uses Python’s format-string capability with two values, not just one. Hence, there are two %s symbols in the string and a tuple of values to insert: (offset, dt).

Finally, we return an HttpResponse of the HTML.

With that view function and URLconf written, start the Django development server (if it’s not already running), and visit http://127.0.0.1:8000/time/plus/3/ to verify it works.

Then try http://127.0.0.1:8000/time/plus/5/.

Then http://127.0.0.1:8000/time/plus/24/.

Finally, visit http://127.0.0.1:8000/time/plus/100/ to verify that the pattern in your URLconf only accepts one- or two-digit numbers; Django should display a “Page not found” error in this case, just as we saw in the section “A Quick Note About 404 Errors” earlier.

The URL http://127.0.0.1:8000/time/plus/ (with no hour designation) should also throw a 404.

Django’s Pretty Error Pages

Take a moment to admire the fine web application we’ve made so far – now let’s break it! Let’s deliberately introduce a Python error into our views.py file by commenting out the offset = int(offset) lines in the hours_ahead view:

def hours_ahead(request, offset):
    # try:
    #     offset = int(offset)
    # except ValueError:
    #     raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be  %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

Load up the development server and navigate to /time/plus/3/. You’ll see an error page with a significant amount of information, including a TypeError message displayed at the very top: “unsupported type for timedelta hours component: str” (Figure 2-3).

Django Views and URLconfs - Django's error page
Figure 2-3: Django’s error page

What happened? Well, the datetime.timedelta function expects the hours parameter to be an integer, and we commented out the bit of code that converted offset to an integer. That caused datetime.timedelta to raise the TypeError. It’s the typical kind of small bug that every programmer runs into at some point.

The point of this example was to demonstrate Django’s error pages. Take some time to explore the error page and get to know the various bits of information it gives you. Here are some things to notice:

  • At the top of the page, you get the key information about the exception: the type of exception, any parameters to the exception (the "unsupported type" message in this case), the file in which the exception was raised, and the offending line number.
  • Under the key exception information, the page displays the full Python traceback for this exception. This is similar to the standard traceback you get in Python’s command-line interpreter, except it’s more interactive. For each level (“frame”) in the stack, Django displays the name of the file, the function/method name, the line number, and the source code of that line.
  • Click the line of source code (in dark gray), and you’ll see several lines from before and after the erroneous line, to give you context. Click “Local vars” under any frame in the stack to view a table of all local variables and their values, in that frame, at the exact point in the code at which the exception was raised. This debugging information can be a great help.
  • Note the “Switch to copy-and-paste view” text under the “Traceback” header. Click those words, and the traceback will switch to an alternate version that can be easily copied and pasted. Use this when you want to share your exception traceback with others to get technical support – such as the kind folks in the Django IRC chat room or on the Django users mailing list.
  • Underneath, the “Share this traceback on a public web site” button will do this work for you in just one click. Click it to post the traceback to dpaste, where you’ll get a distinct URL that you can share with other people.
  • Next, the “Request information” section includes a wealth of information about the incoming web request that spawned the error: GET and POST information, cookie values, and meta information, such as CGI headers. Appendix F has a complete reference of all the information a request object contains.
  • Below the “Request information” section, the “Settings” section lists all of the settings for this particular Django installation. All the available settings are covered in detail in Appendix D.

The Django error page is capable of displaying more information in certain special cases, such as the case of template syntax errors. We’ll get to those later, when we discuss the Django template system. For now, uncomment the offset = int(offset) lines to get the view function working properly again.

The Django error page is also really useful if you are the type of programmer who likes to debug with the help of carefully placed print statements.

At any point in your view, temporarily insert an assert False to trigger the error page. Then, you can view the local variables and state of the program. Here’s an example, using the hours_ahead view:

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    assert False
    html = "<html><body>In %s hour(s), it will be  %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

Finally, it’s obvious that much of this information is sensitive – it exposes the innards of your Python code and Django configuration – and it would be foolish to show this information on the public Internet. A malicious person could use it to attempt to reverse-engineer your web application and do nasty things.

For that reason, the Django error page is only displayed when your Django project is in debug mode. I’ll explain how to deactivate debug mode in Chapter 13. For now, just know that every Django project is in debug mode automatically when you start it. (Sound familiar? The “Page not found” errors, described earlier in this chapter, work the same way.)

What’s Next?

So far, we’ve been writing our view functions with HTML hard-coded directly in the Python code. I’ve done that to keep things simple while I demonstrated core concepts, but in the real world, this is nearly always a bad idea. Django ships with a simple yet powerful template engine that allows you to separate the design of the page from the underlying code. We’ll dive into Django’s template engine in the next chapter.

<<< Views and URLconfs | Table of Contents | Django Templates >>>

Join the Djangobook Family

Updates, freebies, discounts and more!

No spam. Like, ever. Unsubscribe at any time. Powered by ConvertKit