Python Django template full solution and actual combat

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

Introduction to Django's Template System

The Django template system is a powerful component that allows us to dynamically generate HTML, XML, and other structured text based on the data provided. The templating system is not only easy to use, but also feature-rich. It includes a built-in language: the 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 syntax for dynamically generating HTML, XML, or other markup languages. Let's take a closer look at the basic structure of Django templates.

template syntax

Django templates use two main syntaxes:

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

template inheritance

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

For example, to 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 (include) other templates, which can help you break 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 in another template:

{% include "header.html" %}

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

Configuring Django Templates

Configure the Django templating system

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

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 directory.

Configure the template loading method

The Django templating system can load templates from several locations. By default, Django templateslooks for template files in each application 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 will be templatesfound in a folder at the root of the project.

Configure the template engine

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

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

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

Configure custom template tags and filters

If you have custom template tags and filters, you need to put them in a templatetagsdirectory under an application. Then INSTALLED_APPSadd the application to your 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, and more. 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 elsefor 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 child templates:

<!-- 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 templates 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, and optional arguments, and returns the corresponding URL:

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

csrf_token tag

When using a POST form, csrf_tokenthe tag is used to generate a CSRF token 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 a filter requires parameters, they can be added using a colon (:). Let's take a closer look.

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 in order from left to right:

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

custom filter

In addition to using Django's built-in filters, you can also create your own filters. To do this, you need to create a Python file in a directory under your application templatetags, 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]

You can then use this filter in your templates:

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

Display model data in Django templates

The Django framework separates model data from 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 with a titlefield and a contentfield. In our view function, we can query for 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 template

Then, in our blog_list.htmltemplate, we can use fortags to iterate over 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 %}

Format data using filters

In templates, we can also use filters to format model data. For example, we can use datefilters to format dates, or use truncatecharsfilters 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 templating system plays an important role in actual project development. Below we 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 Two: Create a View

Next, we need to create a view to handle user requests. In this view, we can fetch all 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: Writing Templates

Then, we can create a template to display blog posts. In this template, we use fortags to iterate 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 to use 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.


If it is helpful, please pay more attention to the personal WeChat public account: [Python full perspective] TeahLead_KrisChang, 10+ years of experience in the Internet and artificial intelligence industry, 10+ years of experience in technology and business team management, Tongji Software Engineering Bachelor, Fudan Engineering Management Master, Aliyun certified cloud service senior architect, head of AI product business with hundreds of millions of revenue.

Guess you like

Origin blog.csdn.net/magicyangjay111/article/details/131613937