Open the Current_datetime view. Here's what it says:
From django.http import httpresponseimport datetimedef current_datetime (Request): Now = Datetime.datetime.now () html = "It is now%s."% now return HttpResponse (HTML)
Let's use the Django templating system to modify the view. As a first step, you might have thought of making the following changes:
From django.template import template, Contextfrom django.http import httpresponseimport datetimedef current_datetime ( Request): Now = Datetime.datetime.now () t = Template ("It's Now {current_date}}.") html = T.render (Context ({' Current_date ': now}) return HttpResponse (HTML)
Yes, it does use the templating system, but it doesn't solve the problem that we pointed out at the beginning of this chapter. In other words, the template is still embedded in the Python code and does not really separate the data from the presentation. Let's put the template in a separate file and have the view load the file to fix the problem.
You might first consider saving the template to a location in the file system and reading the contents of the file using Python's built-in file manipulation functions. Assuming the file is saved in/home/djangouser/templates/mytemplate.html, the code will look like this:
From django.template import template, Contextfrom django.http import httpresponseimport datetimedef current_datetime ( Request): Now = Datetime.datetime.now () # Simple-to-the-templates from the filesystem. # This is the bad because it doesn ' t account for missing files! fp = open ('/home/djangouser/templates/mytemplate.html ') t = Template (Fp.read ()) fp.close () html = T.render (Context ({' Current_date ': now}) return HttpResponse (HTML)
However, this approach is not concise for several reasons:
- It does not handle file loss situations. If the file mytemplate.html does not exist or is unreadable, the open () function call throws a IOError exception.
- The location of the template file is hardcoded here. If you use this technique with every view function, you will have to copy the location of the templates. Not to mention a lot of input work!
- It contains a lot of annoying repetitive code. Instead of calling open (), Fp.read (), and Fp.close () every time the template is loaded, you might as well make a better choice.