第7天:Django模板使用与表单
模板的配置
作为web框架,Django提供了模板,用于编写html代码,模板的设计实现了业务逻辑view与现实内容template的解耦。模板包含两部分:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。- 静态部分: 包含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的长度。过滤器相当于一个函数,把当前变量传入过滤器中,然后过滤器根据自己的功能,再返回相应的值,最后再将结果渲染到页面中。
1)基本用法

更多精彩