python Django template full analysis

This article first introduces the basic knowledge of Django template system, then discusses how to install and configure Django template system, then deeply analyzes the basic structure of Django templates, the usage of tags and filters, and explains how to display model data in templates. Finally, Use an actual project example to demonstrate how to use the Django template system in actual development.

An introduction to the Django template system

The Django template system is a powerful component that allows us to dynamically generate structured text such as HTML and XML based on the provided data. The template system is not only easy to use, but also feature-rich. It includes a built-in language: Django Template Language (DTL), a simple, non-intrusive language for defining the structure and logic of templates.

For example, in a Django template, we can use variables and tags to dynamically generate content:

# Django模板示例
{
   
   { book.title }} <!-- 输出: Python编程基础 -->
{% if user.is_authenticated %} <!-- 如果用户已登录 -->
  Hello, {
   
   { user.username }}! <!-- 输出: Hello, John! -->
{% endif %}

In the above code, curly braces { { }}are used to output the value of the variable, and labels {% %}are used to perform logical operations.


The basic structure of the template

Django templates are text files composed of a series of special syntaxes used to dynamically generate HTML, XML or other markup languages. Let's take a closer look at the basic structure of Django templates.

Template syntax

Django templates mainly use two syntaxes:

  • Variables : wrapped in double braces ({ { }}). For example { { variable }}, Django will replace it with the value of the variable.
  • Tags : wrapped in braces and percent signs ({% %}). Tags provide template control structures, such as loops, conditional statements, etc. For example {% for item in list %}...{% endfor %}.

Template inheritance

The Django template system supports template inheritance. This is a DRY (Don't Repeat Yourself) design principle. You can define a base template and then let other templates inherit this base template and override certain parts of it.

For example, define a base template base.html:

<!-- base.html -->
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>

Then, define a subtemplate child.htmlthat inherits base.htmland overrides contentthe block:

<!-- child.html -->
{% extends "base.html" %}

{% block content %}
<p>Hello, Django!</p>
{% endblock %}

Other templates

In addition to inheritance, Django templates also support including other templates, which can help you break your templates into small, reusable parts.

For example, define a template header.html:

<!-- header.html -->
<header>
  <h1>Welcome to My Website</h1>
</header>

Then, include this template within another template:

{% include "header.html" %}

<p>This is the main content...</p>

Configure Django templates

Configuring the Django template system

The Django template system is included in Django projects by default. You can settings.pyfind template configuration information in the project's files:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        ...
    },
]

You can 'DIRS'add the path to the template in the configuration item. By default, Django templateslooks for template files in each application's directory.

Configure template loading method

The Django template system can load templates from multiple locations. By default, Django templateslooks for template files in each app's directory. You can add additional template directories by modifying options TEMPLATESin the configuration 'DIRS'. For example, you can add a global template directory:

# settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

In this configuration, all template files are templateslooked for in folders under the project root directory.

Configure template engine

In TEMPLATESthe configuration, 'BACKEND'options are used to specify which template engine to use. Django uses its own template engine by default, that is django.template.backends.django.DjangoTemplates. You can also switch to other template engines, such as Jinja2:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        ...
    },
]

Note that different template engines may require different configurations and may provide different template languages.

Configure custom template tags and filters

If you have custom template tags and filters, you need to place them in a templatetagsdirectory under an application. Then INSTALLED_APPSadd the application in the configuration, and Django will automatically load your custom template tags and filters:

# settings.py

INSTALLED_APPS = [
    ...
    'myapp',
    ...
]

Detailed explanation of template tags

Tags in the Django template system provide various control structures, including loops, conditional statements, template inheritance, etc. Next we introduce some commonly used tags in detail.

for tag

forTags are used to loop through sequences in templates:

{% for item in item_list %}
    <p>{
   
   { item.name }}</p> <!-- 输出每个项目的名称 -->
{% endfor %}

if tag

ifLabels are used for conditional judgment. You can use elifand elseto perform multi-branch judgment:

{% if user.is_authenticated %}
    <p>Welcome back, {
   
   { user.username }}.</p> <!-- 如果用户已经认证,打印欢迎信息 -->
{% else %}
    <p>Please log in.</p> <!-- 如果用户未认证,提示用户登录 -->
{% endif %}

extends tag and block tag

extendsTags are used for template inheritance, and blocktags are used to define blocks that can be overridden by subtemplates:

<!-- base.html -->
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>

<!-- child.html -->
{% extends "base.html" %}

{% block content %}
<p>Hello, Django!</p>
{% endblock %}

include tag

includeTags are used to include other templates, making the template reusable:

{% include "header.html" %}

url tag

urlTags are used to generate URLs. It accepts the name of a view function or the name of a URL pattern, as well as optional parameters, and returns the corresponding URL:

<a href="{% url 'home' %}">Home</a> <!-- 生成首页的URL -->

csrf_token tag

When using POST forms, csrf_tokentags are used to generate CSRF tokens to prevent cross-site request forgery attacks:

<form method="post">
{% csrf_token %}
<!-- 表单内容 -->
</form>

template filter

In Django templates, filters can modify variables before they are displayed. The syntax for a filter is to add a vertical bar (|) and the name of the filter after the variable name. If the filter requires parameters, they can be added using a colon (:). Let’s find out in detail.

Basic use

For example, we can use datefilters to format dates:

{
   
   { date_var|date:"F j, Y" }} <!-- 输出: July 8, 2023 -->

Use lowera filter to convert text to lowercase:

{
   
   { "Hello World"|lower }} <!-- 输出: hello world -->

link filter

You can also chain multiple filters and they will be executed from left to right:

{
   
   { "Hello World"|lower|capfirst }} <!-- 输出: Hello world -->

Custom filters

In addition to using Django's built-in filters, you can also create your own. To do this, you need to create a Python file in a directory under an application templatetags, then define your filter function in it and register.filterregister it with a decorator:

from django import template

register = template.Library()

@register.filter
def my_filter(value):
    # 这是一个简单的过滤器,它返回值的第一个字符
    return value[0]

Then you can use this filter in your template:

{
   
   { "Hello World"|my_filter }} <!-- 输出: H -->

Display model data in Django template

The Django framework separates model data and template views, which allows us to easily display model data in templates. In the view function we can query the model data and then pass it to the template. In templates, we use special syntax to access and display this data.

Prepare data in the view

Let's say we have a Blogmodel which has a titlefield and a contentfield. In our view function, we can query all blogs:

from django.shortcuts import render
from .models import Blog

def blog_list(request):
    blogs = Blog.objects.all()  # 查询所有的博客
    return render(request, 'blog_list.html', {'blogs': blogs})

Display data in templates

Then, in our blog_list.htmltemplate, we can use fortags to iterate through all blogs and use variable syntax to display the title and content of each blog:

{% for blog in blogs %}
<h2>{
   
   { blog.title }}</h2>  <!-- 展示博客标题 -->
<p>{
   
   { blog.content }}</p>  <!-- 展示博客内容 -->
{% endfor %}

Use filters to format data

In templates, we can also use filters to format model data. For example, we can use datea filter to format a date, or truncatecharsa filter to limit the length of text:

{% for blog in blogs %}
<h2>{
   
   { blog.title }}</h2>
<p>{
   
   { blog.publish_date|date:"F j, Y" }}</p>  <!-- 使用date过滤器格式化发布日期 -->
<p>{
   
   { blog.content|truncatechars:100 }}</p>  <!-- 使用truncatechars过滤器限制内容长度 -->
{% endfor %}

Using Django templates in real projects

The Django template system plays an important role in actual project development. Below we will take a simple blog system as an example to demonstrate how to use Django templates in actual projects.

Step 1: Define your model

First, we need to define a model in our application. In this example, we define a Postmodel to represent blog posts:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)  # 文章标题
    content = models.TextField()  # 文章内容
    pub_date = models.DateTimeField(auto_now_add=True)  # 发布日期

Step 2: Create a view

Next, we need to create a view to handle the user's request. In this view we can get all the blog posts and pass them to the template:

from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all()  # 获取所有的博客文章
    return render(request, 'blog/post_list.html', {'posts': posts})  # 将文章传递给模板

Step 3: Write the template

We can then create a template to display the blog post. In this template, we use fortags to loop through all articles and use variables to display the title and content of the article:

{% for post in posts %}
<h2>{
   
   { post.title }}</h2>
<p>{
   
   { post.content }}</p>
<p>Published on {
   
   { post.pub_date|date:"F j, Y" }}</p>
{% endfor %}

Step 4: Configure URLs

Finally, we need to urls.pyconfigure the URL in the file so that users can access our view:

from django.urls import path
from . import views

urlpatterns = [
    path('posts/', views.post_list, name='post_list'),  # 当用户访问/posts/时,显示博客文章列表
]

The above are the basic steps for using Django templates in actual projects. Through this example, we can see the power and flexibility of the Django template system, which can help us quickly create dynamic web pages.

Guess you like

Origin blog.csdn.net/davice_li/article/details/131758411