How to load templates in the Python Django framework

Source: Internet
Author: User
This article mainly introduces how to load templates in the Python Django framework, which is a basic operation in Django usage, for more information about how to reduce the template loading and calling process and the redundant code of the template, Django provides a convenient and powerful API for loading templates from a disk,

To use this template to load APIs, you must first tell the framework where the template is saved. The saved file is settings. py.

If you follow us step by step, open your settings. py configuration file and find the setting TEMPLATE_DIRS. Its default setting is a tuple with automatically generated comments.

TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths.)

This setting tells Django where the template loading mechanism looks for the template. Select a directory to store the template and add it to TEMPLATE_DIRS:

TEMPLATE_DIRS = ( '/home/django/mysite/templates',)

The following are some notes:

You can specify the desired directory as long as the user running the Web server can read the subdirectories and template files of the directory. If you cannot find a proper place to place the template, we recommend that you create a templates directory in the Django project.

If your TEMPLATE_DIRS contains only one directory, do not forget to add a comma after the directory.

Bad:

# Missing comma!TEMPLATE_DIRS = ( '/home/django/mysite/templates') 
Good:

# Comma correctly in place.TEMPLATE_DIRS = ( '/home/django/mysite/templates',)


Python requires that single-element tuples use commas to eliminate ambiguity with parentheses expressions. This is a common mistake for new users.

If you are using a Windows platform, please include the drive symbol and use a Unix-style slash (/) instead of a backslash (), as shown below:

TEMPLATE_DIRS = ( 'C:/www/django/templates',)

The most convenient way is to use an absolute path (that is, the directory path starting from the root directory of the file system ). If you want to be more flexible and reduce some negative interference, you can use the Django configuration file as the Python code to dynamically build the content of TEMPLATE_DIRS, such:

import os.pathTEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),)

This example uses the magic Python Internal Variable _ file _, which is automatically set to the Python module file name where the code is located. ''OS. path. dirname (_ file _) ''will get the file where it is located, that is, settings. the directory where py is located, and then the OS. path. join this method connects the directory with templates. In windows, it intelligently selects the correct backward slash "" to connect, rather than forward slash "/".

Here we are dealing with python code in the dynamic language. I need to remind you that it is important not to write error code in your setup file. If you introduce syntax errors or running errors here, your Django-powered site will probably be crashed.

After completing the TEMPLATE_DIRS settings, the next step is to modify the view code so that it can use the Django template Loading Function instead of hard coding the template path. Returns the current_datetime view and makes the following changes:

from django.template.loader import get_templatefrom django.template import Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request): now = datetime.datetime.now() t = get_template('current_datetime.html') html = t.render(Context({'current_date': now})) return HttpResponse(html)

In this example, we use the django. template. loader. get_template () function instead of manually loading the template from the file system. The get_template () function uses the Template Name as a parameter to locate the module location in the file system, open the file, and return a compiled Template object.

In this example, the selected template file is current_datetime.html, but there is no direct connection with the. html suffix. You can select any file with any suffix, as long as it is logical. Even selecting a file without a suffix is not a problem.

To determine the location of a template file in your system, the get_template () method automatically connects you to the preset TEMPLATE_DIRS directory and the Template Name parameter you passed in this method. For example, if your TEMPLATE_DIRS directory is set to '/home/django/mysite/templates', the above get_template () you can find a location like/home/django/mysite/templates/current_datetime.html.

If get_template () cannot find the template with the given name, a TemplateDoesNotExist exception is thrown. To understand what will happen, run the python manage. py runserver command in the Django project directory according to Chapter 3 to start the Django development server again. Next, let your browser go to the specified page to activate the current_datetime view (for example, http: // 127.0.0.1: 8000/time /). If your DEBUG item is set to true, and you have not created the current_datetime.html template file, you will see the Django error prompt page, telling you that the TemplateDoesNotExist error has occurred.

Screenshot of a TemplateDoesNotExist error.

This page is similar to the error page we have explained in Chapter 3, except that there is an additional debugging information area: the template loader checks the page afterwards. This area shows the template to which Django is loaded and the cause of each attempt error (for example, the file does not exist ). This information is helpful when you try to debug the template loading error.

Next, create the following template code current_datetime.html file in the template directory:

It is now {{ current_date }}.

Refresh the page in the web browser and you will see the page after the complete resolution.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.