Ways to load templates in Python's Django framework

Source: Internet
Author: User

Ways to load templates in Python's Django framework


To reduce the redundant code of the template loading call process and the template itself, Django provides a handy and powerful API for loading templates from disk

To use this template to load the API, you first have to tell the framework where to save the template. The saved file that you set is settings.py.

If you are following us step by step, open your settings.py configuration file and find the Template_dirs setting here. Its default setting is an empty tuple (tuple), plus some auto-generated annotations.

Template_dirs = (# Put strings here, like '/home/html/django_templates ' or ' c:/www/django/templates '. # Always use Forwar D slashes, even on Windows. # Don ' t forget to the use of absolute paths, not relative paths.)


This setting tells the Django template-loading mechanism where to find the template. Select a directory to hold the template and add it to Template_dirs:

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


Here are some things to note:

You can specify the directory you want, as long as the user running the WEB server can read subdirectories and template files for that directory. If you can't figure out where to put the template, we recommend creating a templates directory in the Django project.

If your template_dirs contains only one directory, don't 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 a comma be used in a single-element tuple to eliminate ambiguity with the parentheses expression. This is a common mistake made by novices.

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

Template_dirs = (' c:/www/django/templates ',)


The easiest way to do this is to use an absolute path (that is, the directory path that starts at the root of the file system). If you want to be more flexible and reduce some of the negative distractions, you can use the Django configuration file as Python code to dynamically build Template_dirs content, such as:

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 resides. "Os.path.dirname (__file__)" will fetch the file itself, that is, the directory where settings.py is located, and then os.path.join this method to connect the directory to templates. If it is under Windows, it intelligently chooses the correct back slash "" to connect instead of forward slash "/".

Here we are dealing with the dynamic language Python code, and I need to remind you that it is important not to write the wrong code in your settings file. If you introduce a syntax error here, or run an error, your django-powered site is likely to be crashed.

After you complete the Template_dirs setup, the next step is to modify the view code so that it uses the Django template load feature instead of hard-coding the template path. Return to the Current_datetime view and make the following modifications:

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 used the function django.template.loader.get_template () instead of manually loading the template from the file system. The Get_template () function takes the template name as an argument, finds the location of the module in the file system, opens the file, and returns a compiled template object.

In this example, the template file we selected is current_datetime.html, but this has no direct connection to 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 (see: http://www.aichengxu.com/view/60780)。

To determine the location of a template file in your system, the Get_template () method automatically connects you with the Template_dirs directory you have set and the template name parameter you passed in the method. For example, your Template_dirs directory is set to '/home/django/mysite/templates ', and the above get_template () call will find you/home/django/mysite/templates/ Current_datetime.html such a position.

If Get_template () cannot find a template for the given name, a Templatedoesnotexist exception will be thrown. To find out what's going on, let's run the Python manage.py runserver command in the Django project directory and start the Django Development server again as part of the third chapter. Next, tell your browser to navigate to the specified page to activate the Current_datetime view (such as http://127.0.0.1:8000/time/). Assuming that your debug entry is set to True and you have not created current_datetime.html This template file, you will see a Django error page that tells you that a templatedoesnotexist error has occurred.

Screenshot of a templatedoesnotexist error.


This page is similar to the error page we explained in chapter III, except for a piece of debug information area: The template loader post-mortem check area. This area shows which template Django will load, the reason for each attempt to make an error (e.g., file does not exist, etc.). This information can be very helpful when you try to debug a template loading error.

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



Refresh the page in a Web browser and you'll see the full parsed page.


Python Tutorial "

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Ways to load templates in Python's Django framework

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.