Table of Contents
Ordering notice
Home Backend Development Python Tutorial Django Basics Tutorial - Templates

Django Basics Tutorial - Templates

Oct 17, 2016 pm 02:16 PM

Note: The python version is 3.3.1, the Django version is 1.5.1, and the operating system is Windows 7. There are some differences in other versions. Readers can explore by themselves.

You may have discovered this problem in the previous chapter, that is, when the view returns text, the HTML code is hard-coded in the python code. Such as %s and so on. Writing like this often makes the program more complicated, and it becomes very troublesome once modified. Moreover, HTML code programmers may not necessarily know Python code. Current development generally separates the HTML front-end page and the Python back-end, that is, the front-end is only responsible for displaying the page. , the background is only responsible for processing data and other operations. Therefore, templates are particularly important.

So, what is a template?

A template is a text used to separate the presentation and content of a document. Templates define placeholders and various pieces of basic logic (template tags) that specify how the document should be displayed. Templates are typically used to generate HTML, but Django's templates can also generate documents in any text-based format. Let's learn what a template is from a simple example. (This example comes from DjangoBook2)

 <head><title>Ordering notice</title></head>
 <body>
 <h1 id="Ordering-nbsp-notice">Ordering notice</h1>
 <p>Dear {{ person_name }},</p>
 <p>Thanks for placing an order from {{ company }}. It&#39;s scheduled to
 ship on {{ ship_date|date:"F j, Y" }}.</p>
 <p>Here are the items you&#39;ve ordered:</p>
 <ul>
 {% for item in item_list %}
     <li>{{ item }}</li>
 {% endfor %}
 </ul>
 {% if ordered_warranty %}
     <p>Your warranty information will be included in the packaging.</p>
 {% else %}
     <p>You didn&#39;t order a warranty, so you&#39;re on your own when
     the products inevitably stop working.</p>
 {% endif %}
 <p>Sincerely,<br />{{ company }}</p>
 </body>
 </html>
Copy after login


As shown above, the way to replace python code with {{...}} or {%...%} is template, Like the first {{person_name}} is actually a variable, and {%for....%} or {% if...%} are loops. Without delving into the meaning of the above code, let's learn how to use it step by step.

>>> from django import template
>>> t = template.Template(&#39;My name is {{ name }}.&#39;)
>>> c = template.Context({&#39;name&#39;: &#39;Adrian&#39;})
>>> print(t.render(c))
My name is Adrian.
>>> c = template.Context({&#39;name&#39;: &#39;Fred&#39;})
>>> print(t.render(c))
My name is Fred.
Copy after login


When you see the above code, you may be impatient to try it, but an error occurs on the second line. Generally speaking, the only error that may occur is: 'DJANGO_SETTINGS_MODULE' error. This is because when Django searches for the DJANGO_SETTINGS_MODULE environment variable, it is set in settings.py, and starting the python shell directly will cause it to not know which configuration file to use. For example, assuming mysite is in your Python search path, then DJANGO_SETTINGS_MODULE should be set to: 'mysite.settings'. So in order to avoid the trouble of setting environment variables, we should start the python shell like this.

python manage.py shell

This will save you the trouble of configuring environment variables that you are not familiar with.

Let’s analyze that piece of code.

>>> from django import template  #从django中导入template对象
>>> t = template.Template(&#39;My name is {{ name }}.&#39;)  #使用template对象的Template()方法
>>> c = template.Context({&#39;name&#39;: &#39;Adrian&#39;})  #使用template对象的Context()函数给赋值,比如name的值就是Adrian,Context()的()里面是一个字典
>>> print(t.render(c))   #渲染模板,也就是讲Context赋值后的name的值Adrian替换上面Template()中的{{name}}并输出
My name is Adrian.
>>> c = template.Context({&#39;name&#39;: &#39;Fred&#39;})
>>> print(t.render(c))
My name is Fred.
Copy after login


As you can see from the above example, there are three steps to using templates. 1. Call the Template function; 2. Call the Context function; 3. Call the render function. It's that simple.


Let’s talk about the Context() function through a few codes.

#代码段1:
>>> from django.template import Template,Context
>>> t=Template(&#39;hello,{{name}}&#39;)
>>> for name in (&#39;A&#39;,&#39;B&#39;,&#39;C&#39;):
...     print(t.render(Context({&#39;name&#39;:name})))
...
hello,A
hello,B
hello,C
#代码段2:
>>> from django.template import Template,Context
>>> person={&#39;name&#39;:&#39;Thunder&#39;,&#39;age&#39;:&#39;108&#39;}
>>> t=Template(&#39;{{person.name}} is {{person.age}} years old!&#39;)
>>> c=Context({&#39;person&#39;:person})#后面的这个person是一个字典
>>> t.render(c)
&#39;Thunder is 108 years old!&#39;
#代码段3:
>>> from django.template import Template,Context
>>> t=Template(&#39;Item 2 is {{items.2}}&#39;)#items.2的意思是调用items列表的第3个元素,因为列表的索引是从0开始的
>>> c=Context({&#39;items&#39;:[&#39;Apple&#39;,&#39;Banana&#39;,&#39;Orange&#39;]})
>>> t.render(c)
&#39;Item 2 is Orange&#39;
Copy after login


Note: items.2 above cannot be items.-1 or any other negative index.

Take a good look at the three pieces of code above. Are you just drawing inferences? Also by default, if a variable does not exist, the template system will display it as an empty string and do nothing to indicate failure.



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Scientific Computing: A Detailed Look Python for Scientific Computing: A Detailed Look Apr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles