Python+django+sae Series Tutorial-----Django templates

Source: Internet
Author: User
Tags timedelta

In this chapter, we start with the template, in the previous chapters, you may have noticed that we go back to the text in a way that is a bit of a special example view.

That. HTML directly in hard-coded Python where code.

This is really a little bt.

def current_datetime (Request): Now    = Datetime.datetime.now ()    html = "

Let's say we learned the template. It's not going to be in this way BT, and then the template in Django is actually an HTML file. Let me first look at a simple example:

</p>{% Else%} <p> you do not order warranty requirements, so assume that the machine stops executing you will be responsible for yourself. </p>{% endif%}<p> Zhang San, <br/>{{company}}</p></body>

Text enclosed in two curly braces (for example, {{person_name}}) is called a variable (variable). This means that the value of the specified variable is inserted here.


Text enclosed by curly braces and a semicolon (such as {% if Ordered_warranty%}) is a template tag. Label (tag) definition is more clear. That is, the label that notifies the template system that some work is complete.

In fact, it's where the code and the statement are written.


The second paragraph of this template has a sample of filter filters, which is one of the most convenient ways to convert variable output formats.

As in this example, {{ship_date|date: "F J, Y"}}, we pass the variable ship_date to the date filter. Specify the number of references "F j,y" at the same time. The date filter formats the output according to the number of parameters. The filter is with a pipe character (|) To invoke. You can see the UNIX pipe symbol in detail.

In fact, I prefer to filter this information in the background. Because we cannot ask the artist or the person who participates in the layout design to have too many programming foundation. So the tutorial on the template of the introduction of temporary can be ignored.


Knowing the template, we're now going to create a template and see how it's applied in the view. Here we first create a directory named template, which will be placed in our editing template, is the HTML file.

Then we need to find "template_dirs =" in the setting.py file, and then tell 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 = ("Bidding/templates")
In fact, the folder and the path can be self-made, just need to set in the setting is OK, here can also use absolute path such as:

Template_dirs = (    ' c:/www/django/templates ',)
After the template_dirs is set up, the next step is to change 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 for such changes as the following:

From django.shortcuts import render_to_responseimport datetimedef current_datetime (Request): Now    = Datetime.datetime.now ()    return render_to_response (' current_datetime.html ', {' current_date ': now})

We no longer need to import get_template, template, Context, and HttpResponse.

Instead, we import django.shortcuts.render_to_response.

Import datetime continues to persist.

In the Current_datetime function. We still do now calculations. But template loading, context creation, template parsing, and HttpResponse creation are all in the call to Render_to_response (). Because Render_to_response () returns the HttpResponse object, we only need to return the value in the view.


The first parameter of Render_to_response () must be the name of the template to use.

Given a second parameter, the reference must be the dictionary used to create the Context for the template. Assume that you do not provide a second number of parameters. Render_to_response () uses an empty dictionary.




This {' Current_date ': now} needs to be explained: Now is the variable in the view. The current_date is a variable in the template. In fact, assume that these two variables have been said. We can simplify writing this:

From django.shortcuts import render_to_responseimport datetimedef current_datetime (Request):    current_date = Datetime.datetime.now ()    return render_to_response (' current_datetime.html ', locals ())
Keeping all the templates in one folder can make things difficult to control.

You might consider storing the template in a subfolder of your template folder. This is good.

Can also do this:

Return Render_to_response (' dateapp/current_datetime.html ', locals ())
Windows users must use a slash instead of a backslash. Said so much. I think you must want to try this template as much as I do. Views.py's changes have been described above. Here we create a template current_datetime.html:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" >

Then we put the current_datetime.html file into templates.


Before this, make sure that a few steps are complete.
1. Changed template_dirs = ("Bidding/templates") in setting
2. Changed the views.py

From django.shortcuts import render_to_responseimport datetimedef current_datetime (Request):    current_date = Datetime.datetime.now ()    return render_to_response (' current_datetime.html ', locals ())
Then upload the code to see the effect.




The following we look at the Include template tag, which is the template can be nested templates, first we create a template folder inside a base folder, in this folder we are ready to put on the page top and bottom template.
Top.html:

<div style= "background: #eeeeee; width:100%;height:60px;" >    Learning Python is a happy process----{Author}}</div>

Bottom.html:

<div style= "background: #eeeeee; width:100%;height:30px;" >    All rights reserved----{{Author}}</div>
Then we create a new template, put him in the template root folder, named template_include.html

Template_include.html:

And then we're changing the previous Hours_ahead view:
def hours_ahead (Request, offset):    try:        offset = int (offset)    except ValueError:        raise Http404 ()    DT = Datetime.datetime.now () + Datetime.timedelta (hours=offset)    author= "Hemeng80"    return Render_to_response (' template_include.html ', locals ())
So far, our template paradigm is just a few snippets of HTML, but in practice, you'll use the Django template system to create an entire HTML page.

This leads to a common Web development problem: throughout the site. How can you reduce the number of repetitive and redundant code that is caused by a shared page area (for example, site navigation)?


The traditional approach to solving this problem is to use the server-side includes. You can use this directive in an HTML page to embed a Web page in one of the other pages. In fact, Django supports such a method through the {% include%} just described.

But the preferred way to solve such problems with Django is to use a more elegant strategy-template inheritance.


First we create a base class template named Base.html:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" >
Now we have a basic template. We are able to create a hello_base.html template to use it:

{% extends "base.html"%} {% block title%} Welcome {% Endblock%}{% block content%}<p> then my first Python program: {{MyString}}.</p>{% endblock%}
In the transformation of views.py:

#-*-Coding:utf-8-*-from django.http import httpresponsefrom django.shortcuts import render_to_responseimport datetime def hello (request):    return HttpResponse (' Hello World ') def current_datetime (request):    current_date = Datetime.datetime.now ()    return render_to_response (' current_datetime.html ', Locals ()) def hours_ahead (Request, Offset):    try:        offset = int (offset)    except ValueError:        raise Http404 ()    dt = Datetime.datetime.now () + Datetime.timedelta (hours=offset)    author= "Hemeng80"    return render_to_response (' template_include.html ' , locals ()) def hello_base (request):    MyString = ' Hello World '    return render_to_response (' hello_base.html ', Locals ())
Under Configuration urls.py:

From Django.conf.urls import patterns, include, url# uncomment the next and lines to enable the admin:# from Django.contri B Import admin# admin.autodiscover () Urlpatterns = Patterns ("',    # Examples:    # URL (r ' ^$ ', ' Bidding.views.home ', Name= ' home '),    # URL (r ' ^bidding/', include (' Bidding.foo.urls ')),    # uncomment the Admin/doc line below to enable Admin documentation:    # URL (r ' ^admin/doc/', include (' Django.contrib.admindocs.urls ')),    # uncomment the next Line to enable the admin:    # URL (r ' ^admin/', include (Admin.site.urls)),    URL (r ' ^hello/$ ', ' Bidding.views.hello ' ),    url (r ' ^time/$ ', ' Bidding.views.current_datetime '),    url (r ' ^time/plus/(\d{1,2})/$ ', ' Bidding.views.hours_ahead '),    url (r ' ^hello_base/$ ', ' Bidding.views.hello_base '),)
When you look at the results of the program execution, you will be able to understand the meaning of the template's inclusion and inheritance.








Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Python+django+sae Series Tutorial-----Django templates

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.