Your Second View: Dynamic URLs

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.

A Word About Pretty URLs – If you’re experienced in another Web development platform, such as PHP or Java, you may be thinking, “Hey, let’s use a query string parameter!”, something like /time/plus?hours=3, in which the hours would be designated by the hours parameter in the URL’s query string (the part after the ?).

You can do that with Django (and we’ll tell you how later, if you really must know), but one of Django’s core philosophies is that URLs should be beautiful. The URL /time/plus/3/ is far cleaner, simpler, more readable, easier to recite to somebody aloud and … just plain prettier than its query string counterpart. Pretty URLs are a sign of a quality Web application.

Django’s URLconf system encourages pretty URLs by making it easier to use pretty URLs than not to.

Wildcard URLpatterns – Continuing with our hours_ahead example, let’s put a wildcard in the URLpattern. As we mentioned previously, a URLpattern is a regular expression; hence, we can use the regular expression pattern \d+ to match one or more digits:

from django.conf.urls.defaults import *

from mysite.views import current_datetime, hours_ahead

urlpatterns = patterns('',    

          (r'^time/$', current_datetime),    

          (r'^time/plus/\d+/$', hours_ahead),)

This 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 99 hours. That means we want to allow either one- or two-digit numbers—in regular expression syntax, that translates into \d{1,2}:

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

Note – When building Web applications, it’s always important to consider the most outlandish data input possible, and decide whether or not the application should support that input. We’ve curtailed the outlandishness here by limiting the offset to 99 hours. And, by the way, The Outlandishness Curtailers would be a fantastic, if verbose, band name.

Now that we’ve designated a wildcard for the URL, we need a way of passing that 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}:

    (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 current_datetime view, looks like this:

from django.conf.urls.defaults import *

from mysite.views import current_datetime, hours_ahead

 urlpatterns patterns('',    

          (r'^time/$', current_datetime),    

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

With that taken care of, let’s write the hours_ahead view.

Coding Order – In this example, we wrote the URLpattern first and the view second, but in the previous example, we wrote the view first, then the URLpattern. Which technique is better? Well, every developer is different. If you’re a big-picture type of person, it may make the most sense to you to write all of the URLpatterns for your application at the same time, at the start of your project, and then code up the views. This has the advantage of giving you a clear to-do list, and it essentially defines the parameter requirements for the view functions you’ll need to write. If you’re more of a bottom-up developer, you might prefer to write the views first, and then anchor them to URLs afterward. That’s OK, too. In the end, it comes down to which technique fits your brain the best. Both approaches are valid.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. Add this to views.py:

 def hours_ahead(request, offset):    

      offset = int(offset)    

      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 step through this code one line at a time:

  • Just as we did for our current_datetime view, we import the class django.http.HttpResponse and the datetime module.
  • The view function, hours_ahead, takes two parameters: request and offset.
  • request is an HttpRequest object, just as in current_datetime. We’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 strings will always be strings, not integers, even if the string is composed of only digits, such as ’21’.
  • We 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.
  • The first thing we do within the function is call int() on offset. This converts the 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’. However, in this example we don’t have to worry about catching that exception, because we can be certain offset will be a string containing only digits. We know that because the regular-expression pattern in our URLconf— (\d{1,2})—captures only digits. This illustrates another nicety of URLconfs: they provide a fair level of input validation.
  • The next line of the function shows why we called int() on offset. On this line, we calculate the current time plus a time offset of offset hours, storing the result in dt. 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—again, just as we did in current_datetime.

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 “404 Errors” section earlier. The URL http://127.0.0.1:8000/time/plus/ (with no hour designation) should also throw a 404.

If you’re following along while coding at the same time, you’ll notice that the views.py file now contains two views. (We omitted the current_datetime view from the last set of examples for clarity.) Put together, views.py should look like this:

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) 

def hours_ahead(request, offset):    

   offset = int(offset)   

   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)

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),]

If you’re experienced in another web development platform, you may be thinking, “Hey, let’s use a query string parameter!” – something like /time/plus?hours=3, in which the hours would be designated by the hours parameter in the URL’s query string (the part after the ‘?’).You can do that with Django, but one of Django’s core philosophies is that URLs should be beautiful.

The URL /time/plus/3/ is far cleaner, simpler, more readable, easier to recite to somebody aloud and just plain prettier than its query string counterpart. Pretty URLs are a characteristic of a quality web application. Django’s URLconf system encourages pretty URLs by making it easier to use pretty URLs than not to.

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, HttpResponseimport 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.)

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.

404 Errors
Django’s Pretty Error Pages

Get industry recognized certification – Contact us

keyboard_arrow_up