Using templates in views

You've learned the basics of using the template system; now let's use this knowledge to create a view.

Recall the current_datetime view in mysite.views, which we started in the previous chapter. Here's what it looks like:

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 change this view to use Django's template system. At first, you might think to do something like this:

from django.template import Template, Context 
from django.http import HttpResponse 
import datetime 
 
def current_datetime(request): 
 
    now = datetime.datetime.now() 
    t = Template("<html><body>It is now {{ current_date }}. 
         </body></html>") 
    html = t.render(Context({'current_date': now})) 
    return HttpResponse(html) 

Sure, that uses the template system, but it doesn't solve the problems we pointed out in the introduction of this chapter. Namely, the template is still embedded in the Python code, so true separation of data and presentation isn't achieved. Let's fix that by putting the template in a separate file, which this view will load.

You might first consider saving your template somewhere on your filesystem and using Python's built-in file-opening functionality to read the contents of the template. Here's what that might look like, assuming the template was saved as the file /home/djangouser/templates/mytemplate.html:

from django.template import Template, Context 
from django.http import HttpResponse 
import datetime 
 
def current_datetime(request): 
 
    now = datetime.datetime.now() 
    # Simple way of using templates from the filesystem. 
    # This is 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) 

This approach, however, is inelegant for these reasons:

  • It doesn't handle the case of a missing file. If the file mytemplate.html doesn't exist or isn't readable, the open() call will raise an IOError exception.
  • It hard-codes your template location. If you were to use this technique for every view function, you'd be duplicating the template locations. Not to mention it involves a lot of typing!
  • It includes a lot of boring boilerplate code. You've got better things to do than to write calls to open(), fp.read(), and fp.close() each time you load a template.

To solve these issues, we'll use template loading and template directories.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset