Friday, January 6, 2017

Django - 012 - Our second view - dynamic content

Our Hello World view was instructive in demonstrating the basics of how Django works, but it was not an example of a dynamic web page, because the content of the page is always the same. Everytime you view /hello/, you will see the same thing, it might as well be a static HTML file.

For our second view, let us create something more dynamic - a webpage that displays the current date and time. This is a nice, simple next step , because it does not involve a database or any user input - just the output of your server's internal clock. It is only marginally more exciting than Hello World, but it will demonstrate a few new concepts. This view needs to do two things:

  1. calculate the current date and time
  2. return an HttpResponse containing that value.


If you have experience with Python, you know that Python includes a datetime module for calculating dates. Here is how to use it:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2017, 1, 5, 20, 5, 7, 293320)
>>> print now
2017-01-05 20:05:07.293320
>>>

That is simple enough, and it has nothing to do with Django. It is just Python code. (We want to emphasize that you should be aware of what code is just Python vs. code that is Django specific. As you learn Django, we want you to be able to apply your knowledge to other Python projects that do not 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 is what the updated views.py looks like:

from django.http import HttpResponse
import datetime

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

def my_homepage_view(request):
  return HttpResponse("Welcome to my Home Page")

def current_datetime(request):
  now = datetime.datetime.now()
  html = "<html> <body>  It is now %s. </body></html>" %now
  return HttpResponse(html)

Let us step through the changes we have made to views.py to accomodate the current_datetime view.

We have added and 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 following 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-01-05 20:05:07.293320". This will result in an HTML string such as "<html><body> It is now 2017-01-05 20:05:07.293320. <body><html>".
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 URL pattern to urls.py to tell Django which URL should handle this view. Something like /time/ would make sense:

from django.conf.urls import include, url
from django.contrib import admin
from myD3site.views import hello
from myD3site.views import my_homepage_view , current_datetime

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

We have made two changes here. First, we imported the current_datetime function at the top. Second, and more importantly, we added a URL pattern mapping the URL /time/ to that new view. Getting the hang of this? With the view written and URLconf updated, fire up the runserver :

$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
January 06, 2017 - 00:25:34
Django version 1.10.4, using settings 'myD3site.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


and visit: http://127.0.0.1:8000/time/ in your browser.



You should see the current date and time. If you don't see your local time, it is likely because the default timezone in your settings.py is set to UTC.


No comments:

Post a Comment