Site icon Tutorial

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

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

Template Loading

Django provides a convenient and powerful API for loading templates from the filesystem, with the goal of removing redundancy both in your template-loading calls and in your templates themselves. In order to use this template-loading API, first you’ll need to tell the framework where you store your templates. The place to do this is in your settings file – the settings.py file that I mentioned last chapter, when I introduced the ROOT_URLCONF setting. If you’re following along, open your settings.py and find the TEMPLATES setting. It’s a list of configurations, one for each engine:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]

BACKEND is a dotted Python path to a template engine class implementing Django’s template backend API. The built-in backends are django.template.backends.django.DjangoTemplates and django.template.backends.jinja2.Jinja2.

Since most engines load templates from files, the top-level configuration for each engine contains three common settings:

Template Directories

DIRS, by default, is an empty list. To tell Django’s template-loading mechanism where to look for templates, pick a directory where you’d like to store your templates and add it to DIRS, like so:

    'DIRS': [          

              '/home/html/templates/site',          

              '/home/html/templates/default',       ],

There are a few things to note:

      'DIRS': [os.path.join(BASE_DIR, 'templates')],
   'DIRS':     
    [      
    'C:/www/django/templates',     
    ]

As we have not yet created a Django app, I am going to use a very simple configuration to demonstrate how template loading works. First, you will have to set DIRS to [os.path.join(BASE_DIR,’templates’)] as per the example above. Your settings file should now look like this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {

With DIRS set, the next thing to do is create a \templates directory inside your root \mysite folder. When you are finished, your folder structure should look like this:

\mysite_project 

        \mysite       

            \mysite        

             \templates        

           manage.py

Next step is to change the view code to use Django’s template-loading functionality rather than hard-coding the template paths. Returning to our current_datetime view, let’s change it like so:

#mysite\mysite\views.py

from django.template.loader import get_template
from django.http import HttpResponse
import datetime

def current_datetime(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render({'current_date': now})
return HttpResponse(html)

Generally, you will use a Django template loader rather than using the low-level template API as in the previous examples. In this example, we’re using the function django.template.loader.get_template() rather than loading the template from the filesystem manually. The get_template() function takes a template name as its argument, figures out where the template lives on the filesystem, opens that file, and returns a compiled Template object.

Also note the difference between the render() method here and the previous examples. In the previous examples we are calling django.template.Template.render, which requires you to pass in a Context object. get_template() returns a backend-dependent Template from django.template.backends.base.Template, in which the render() method only accepts a dictionary object, not a Context object.

Our template in this example is current_datetime.html, but there’s nothing special about that .html extension. You can give your templates whatever extension makes sense for your application, or you can leave off extensions entirely.

To determine the location of the template on your filesystem, get_template() will look in order:

To see what a template exception looks like, fire up the Django development server again by running python manage.py runserver within your Django project’s directory. Then, point your browser at the page that activates the current_datetime view (e.g., http://127.0.0.1:8000/time/). Assuming your DEBUG setting is set to True and you haven’t yet created a current_datetime.html template, you should see a Django error page highlighting the TemplateDoesNotExist error

This error page is similar to the one explained earlier, with one additional piece of debugging information: a “Template-loader postmortem” section. This section tells you which templates Django tried to load, along with the reason each attempt failed (e.g., “File does not exist”). This information is invaluable when you’re trying to debug template-loading errors.

To solve our missing template problem, let’s create the current_datetime.html file using the following template code:

# \mysite_project\mysite\templates\current_datetime.html

<html>
<body>
It is now {{ current_date }}
</body>
</html>
It is now {{ current_date }}.

Save this file to the \mysite\templates directory you created previously. Refresh the page in your web browser, and you should see the fully rendered page

render()

So far, I’ve shown you how to load a template, fill a Context and return an HttpResponse object with the result of the rendered template. Next step was to optimize it to use get_template() instead of hard-coding templates and template paths.

Django’s developers recognized that, because this is such a common idiom, Django needed a shortcut that could do all this in one line of code. This shortcut is a function called render(), which lives in the module django.shortcuts. Most of the time, you’ll be using render() rather than loading templates and creating Context and HttpResponse objects manually – however, it’s useful to remember the complete process because it does come in handy for some non-standard use-cases.

Here’s the ongoing current_datetime example rewritten to use render():

from django.shortcuts import render
import datetime

def current_datetime(request):
now = datetime.datetime.now()
return render(request, 'current_datetime.html', {'current_date': now})

What a difference! Let’s step through the code changes:

The first argument to render() is the request, the second is the name of the template to use. The third argument, if given, should be a dictionary to use in creating a Context for that template. If you don’t provide a third argument, render() will use an empty dictionary.

Template Subdirectories

It can get unwieldy to store all of your templates in a single directory. You might like to store templates in subdirectories of your template directory, and that’s fine.

In fact, I recommend doing so; some more advanced Django features (such as the generic views system) expect this template layout as a default convention. It also gives your templates their own namespace, the utility of which we will explore later in the book when we start building Django apps.

Storing templates in subdirectories of your template directory is easy. In your calls to get_template(), just include the subdirectory name and a slash before the template name, like so:

    t = get_template('dateapp/current_datetime.html')

Because render() is a small wrapper around get_template(), you can do the same thing with the second argument to render(), like this:

    return render(request, 'dateapp/current_datetime.html', {'current_date': now})

There’s no limit to the depth of your subdirectory tree. Feel free to use as many subdirectories as you like. As with all other methods in this chapter, Windows users must remember to use forwardslashes (/) in path names, not backslashes (\).

The include Template Tag

Now that we’ve covered the template-loading mechanism, we can introduce a built-in template tag that takes advantage of it: {% include %}.

This tag allows you to include the contents of another template. The argument to the tag should be the name of the template to include, and the template name can be either a variable or a hard-coded (quoted) string, in either single or double quotes.

Anytime you have the same code in multiple templates, consider using an {% include %} to remove the duplication. These two examples include the contents of the template nav.html. The examples are equivalent and illustrate that either single or double quotes are allowed:

{% include 'nav.html' %}
{% include "nav.html" %}

This example includes the contents of the template includes/nav.html:

{% include 'includes/nav.html' %}

This example includes the contents of the template whose name is contained in the variable template_name:

{% include template_name %}

the {% include %} tag also allows relative paths:

{% include './nav.html' %}
{% include '../nav_base.html' %}


As in get_template(), the file name of the template is determined by either adding the path to the \templates directory in the current Django app (if APPS_DIR is True) or by adding the template directory from DIRS to the requested template name. Included templates are evaluated with the context of the template that’s including them.

For example, consider these two templates:

# mypage.html

<html>
<body>
{% include "includes/nav.html" %}
<h1>{{ title }}</h1>
</body>
</html>

# includes/nav.html

You are in: {{ current_section }}

If you render mypage.html with a context containing current_section, then the variable will be available in the “included” template, as you would expect.

If, in an {% include %} tag, a template with the given name isn’t found, Django will do one of two things:

There is no shared state between included templates – each include is a completely independent rendering process. Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered – not blocks that can be overridden by, for example, an extending template.

Back to Tutorial

Exit mobile version