第7天:Django模板使用与表单

模板的配置

作为web框架,Django提供了模板,用于编写html代码,模板的设计实现了业务逻辑view与现实内容template的解耦。模板包含两部分:

  • 静态部分: 包含html、css、js
  • 动态部分: 模板语言

settings.py中DIRS定义一个目录列表,模板引擎按列表顺序搜索目录以查找模板文件,通常是在项目的根目录下创建templates目录

 模板文件: book/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试项目逻辑</title>
</head>
<body>

<h1>{{ test }}</h1>

</body>
</html>
book/index.html

视图渲染模板

from django.shortcuts import render
from django.views.generic import View



class IndexView(View):
    def get(self, request):
        context = {'test': '测试项目逻辑'}
        return render(request, 'book/index.html', context)
book.views

路由url配置

# book.url
from django.conf.urls import url
from .views import IndexView

urlpatterns = [
    url(r'^$', IndexView.as_view(), name='index'),
]


#demo.url
urlpatterns = [
    ...
    url(r'^book/', include('book.urls', namespace='book')),
]
url配置

浏览器访问http://127.0.0.1/book

变量

视图,传入参数

from django.shortcuts import render
from django.views.generic import View
from .models import Book


class IndexView(View):
    def get(self, request):
        book = Book.objects.get(id=1)
        context = {'username': '何波安', 'age': 18, 'book': book}
        return render(request, 'book/index.html',context)
book.views

模板文件index.html:使用{{ 变量名 }}的方式引用,  如果变量不存在,则取出空字符串

<body>

姓名: {{ username }} <br/>
年龄: {{ age }}      <br/>
图书: {{ book.title }}

</body>
book/index.html

标签

1)for 循环标签

{% for item in 列表 %}
执行循环逻辑
{{ forloop.counter }}获取当前是第几次循环,从1开始
{% empty %}
列表为空或不存在时执行此逻辑
{% endfor %}
class IndexView(View):
    def get(self, request):
        books = Book.objects.all()
        context = {'booklist': books}
        return render(request, 'book/index.html',context)
books.views
<body>

<ul>
    {% for book in booklist %}
        <span style="color: red"> {{ forloop.counter }}</span> -{{ book.title }}<br />
    {% endfor %}
</ul>

</body>
book/index.html

 2)if标签

{% if ... %}
逻辑1
{% elif ... %}
逻辑2
{% else %}
逻辑3
{% endif %}
<ul>
    {% for book in booklist %}
        {% if book.id <= 2 %}
            <li style="background: red">{{ book.title }}</li>
        {% elif book.id == 3 %}
            <li style="background: green">{{ book.title }}</li>
        {% else %}
            <li style="background: blue">{{ book.title }}</li>
        {% endif %}
    {% endfor %}
</ul>

</body>
book/index.html

过滤器

过滤器是通过管道"|"进行使用的,例如{{ name | length }},将返回name的长度。过滤器相当于一个函数,把当前变量传入过滤器中,然后过滤器根据自己的功能,再返回相应的值,最后再将结果渲染到页面中。

常用的过滤器

  • length,返回字符串、列表、元组、字典的元素个数
    • 变量|length
  • default,如果变量不存在时则返回默认值
    • 变量|default:默认值
  • date,用于对日期类型的值进行字符串格式化

    • 常用的格式化如下
      • Y表示年,格式为4位,y表示两位的年
      • m表示月,格式为01,02,12等
      • j表示日,格式为1,2等
      • H表示时,24进制,h表示12进制的时
      • i表示分,为0-59
      • s表示秒,为0-59
    • 日期|date:'Y年m月j日 H时i分s秒'

过滤器演练

场景: 当用户没有自定义个性签名的时候,使用default传递值,如下:

class IndexView(View):
    def get(self, request):
        context = {'signature': '世界真的好赞'}
        return render(request, 'book/index.html',context)

index.html

个性签名: {{ signature| default:'这个人真懒,什么都没有留下~' }}

当没有定义signature,则会显示"这个人真懒,什么都没有留下~"

class IndexView(View):
    def get(self, request):
        context = {
            #'signature': '世界真的好赞'
        }
        return render(request, 'book/index.html',context)

模板继承

模板继和类的继承含义是一样的,主要是为了提高代码重用,减轻开发人员的工作量,典型应用:

  • 网站的头部
  • 尾部信息

父模板

  • 如果发现一段代码在多个模板中出现,那就应该把这段代码内容定义到父模板中
  • 父模板中也可以使用上下文中传递过来的数据
  • 父模板定义在templates文件目录下
  • block标签:用于在父模板中预留区域,留给子模板填充差异性的内容
{% block 名称 %}
预留区域,可以编写默认内容,也可以没有默认内容
{% endblock 名称 %}

子模板

  • 子模板定义在templates/应用文件目录下
  • extends标签:继承,写在子模板文件的第一行

  • 子模版不用填充父模版中的所有预留区域,如果子模版没有填充,则使用父模版定义的默认值

  • 填充父模板中指定名称的预留区域
{% block 名称 %}
实际填充内容
{{ block.super }} 用于获取父模板中block的内容,也可以不获取
{% endblock 名称 %}

 模板继承演练

 定义父子模板文件目录

原文地址:https://www.cnblogs.com/sellsa/p/10808594.html