为了方便任然在前面编辑的mysite项目中进行编辑
一、在mysite/ learn/views.py 中写一个首页的视图
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
二、在 learn目录下新建一个 templates 文件夹,里面新建一个 home.html
默认配置下,Django 的模板系统会自动找到app下面的templates文件夹中的模板文件。
目录的结构是这样的:
mysite
├── learn
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── home.html
│ ├── tests.py
│ └── views.py
├── manage.py
└──mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
三、在 home.html 中写一些内容
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
欢迎光临你的第一个模板
</body>
</html>
四、更改 mysite/urls.py
将视图函数对应到网址
path('home/', learn_views.home, name='home'),
五、创建数据库表
python manage.py migrate
六、网站通用模板
网站模板的设计,一般的,我们做网站有一些通用的部分,比如 导航,底部,访问统计代码等等
nav.html, bottom.html, tongji.html
6.1在templates 文件夹创建 base.html 来包含这些通用文件(include)
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}默认标题{% endblock %} - 自强学堂</title>
</head>
<body>
{% include 'nav.html' %}
{% block content %}
<div>这里是默认内容,所有继承自这个模板的,如果不覆盖就显示这里的默认内容。</div>
{% endblock %}
{% include 'bottom.html' %}
{% include 'tongji.html' %}
</body>
</html>
如果需要,写足够多的 block 以便继承的模板可以重写该部分,include 是包含其它文件的内容,就是把一些网页共用的部分拿出来,重复利用,改动的时候也方便一些,还可以把广告代码放在一个单独的html中,改动也方便一些,在用到的地方include进去。其它的页面继承自 base.html 就好了,继承后的模板也可以在 block 块中 include 其它的模板文件。
** 6.2 首页继承base.html**
我们的首页 home.html,继承或者说扩展(extends)原来的 base.html,可以简单这样写,重写部分代码(默认值的那一部分不用改)
{% extends 'base.html' %}
{% block title %}欢迎光临首页{% endblock %}
{% block content %}
{% include 'ad.html' %}
这里是首页,欢迎光临
{% endblock %}
注意:模板一般放在app下的templates中,Django会自动去这个文件夹中找。但 假如我们每个app的templates中都有一个 index.html,当我们在views.py中使用的时候,直接写一个 render(request, ‘index.html’),Django 能不能找到当前 app 的 templates 文件夹中的 index.html 文件夹呢?(答案是不一定能,有可能找错)
七、Django 模板查找机制
Django 查找模板的过程是在每个 app 的 templates 文件夹中找(而不只是当前 app 中的代码只在当前的 app 的 templates 文件夹中找)。各个 app 的 templates 形成一个文件夹列表,Django 遍历这个列表,一个个文件夹进行查找,当在某一个文件夹找到的时候就停止,所有的都遍历完了还找不到指定的模板的时候就是 Template Not Found (过程类似于Python找包)。这样设计有利当然也有弊,有利是的地方是一个app可以用另一个app的模板文件,弊是有可能会找错了。所以我们使用的时候在 templates 中建立一个 app 同名的文件夹,这样就好了。
这就需要把每个app中的 templates 文件夹中再建一个 app 的名称,仅和该app相关的模板放在 app/templates/app/ 目录下面,
例如:项目 zqxt 有两个 app,分别为 tutorial 和 tryit
zqxt
├── tutorial
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── templates
│ │ └── tutorial
│ │ ├── index.html
│ │ └── search.html
│ ├── tests.py
│ └── views.py
├── tryit
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── templates
│ │ └── tryit
│ │ ├── index.html
│ │ └── poll.html
│ ├── tests.py
│ └── views.py
├── manage.py
└── zqxt
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
这样,使用的时候,模板就是 “tutorial/index.html” 和 “tryit/index.html” 这样有app作为名称的一部分,就不会混淆。
八、Django模板的其他应用
实例一,显示一个基本的字符串在网页上
#views.py
from django.shortcuts import render
def home(request):
string = u"我在学习Django,用它来建网站"
return render(request, 'home.html', {'string': string})#在视图中我们传递了一个字符串名称是 string 到模板 home.html,在模板中这样使用它:
#home.html
{{ string }}
实例二,讲解了基本的 for 循环 和 List内容的显示
#views.py
def home(request):
TutorialList = ["HTML", "CSS", "jQuery", "Python", "Django"]
return render(request, 'home.html', {'TutorialList': TutorialList})#在视图中我们传递了一个List到模板 home.html,在模板中这样使用它:
#home.html
教程列表:
{% for i in TutorialList %} #for 循环要有一个结束标记,
{{ i }}
{% endfor %}
简单总结一下:一般的变量之类的用 {{ }}(变量),功能类的,比如循环,条件判断是用 {% %}(标签)
实例三,显示字典中内容:
取字典中内容:
#views.py
def home(request):
info_dict = {'site': u'W3C', 'content': u'各种IT技术教程'}
return render(request, 'home.html', {'info_dict': info_dict})
#home.html
站点:{{ info_dict.site }} 内容:{{ info_dict.content }}#在模板中取字典的键是用点info_dict.site,而不是Python中的 info_dict['site']
还可以这样遍历字典:
{% for key, value in info_dict.items %}
{{ key }}: {{ value }}
{% endfor %}
实例四,在模板进行 条件判断和 for 循环的详细操作:
#views.py
def home(request):
List = map(str, range(100))# 一个长度为100的 List
return render(request, 'home.html', {'List': List})#假如我们想用逗号将这些元素连接起来
#home.html
{% for item in List %}
{{ item }}, #我们会发现最后一个元素后面也有一个逗号,这样肯定不爽,如果判断是不是遍历到了最后一个元素了呢
{% endfor %}
修改:
{% for item in List %}
{{ item }}{% if not forloop.last %},{% endif %} #用变量 forloop.last 这个变量,如果是最后一项其为真,否则为假
{% endfor %}
在for循环中还有很多有用的东西,如下:
变量 描述
forloop.counter 索引从 1 开始算
forloop.counter0 索引从 0 开始算
forloop.revcounter 索引从最大长度到 1
forloop.revcounter0 索引从最大长度到 0
forloop.first 当遍历的元素为第一项时为真
forloop.last 当遍历的元素为最后一项时为真
forloop.parentloop 用在嵌套的 for 循环中,获取上一层 for 循环的 forloop
当列表中可能为空值时用 for empty
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>抱歉,列表为空</li>
{% endfor %}
</ul>
实例五,模板上得到视图对应的网址:
# views.py
def add(request, a, b):
c = int(a) + int(b)
return HttpResponse(str(c))
# urls.py
urlpatterns = patterns('',
path(r'^add/(\d+)/(\d+)/$', 'app.views.add', name='add'),
# template html
{% url 'add' 4 5 %}
还可以使用 as 语句将内容取别名(相当于定义一个变量),多次使用(但视图名称到网址转换只进行了一次)
{% url 'some-url-name' arg arg2 as the_url %}
<a href="{{ the_url }}">链接到:{{ the_url }}</a>
实例六,模板中的逻辑操作:
==, !=, >=, <=, >, < 这些比较都可以在模板中使用,比如:
{% if var >= 90 %}
成绩优秀,Django你没少去吧!学得不错
{% elif var >= 80 %}
成绩良好
{% elif var >= 70 %}
成绩一般
{% elif var >= 60 %}
需要努力
{% else %}
不及格啊,大哥!多去Django学习啊!
{% endif %}
(注意:比较符号前后必须有至少一个空格!)
and, or, not, in, not in 也可以在模板中使用
假如我们判断 num 是不是在 0 到 100 之间:
{% if num <= 100 and num >= 0 %}
num在0到100之间
{% else %}
数值不在范围之内!
{% endif %}
假如我们判断 ‘ziqiangxuetang’ 在不在一个列表变量 List 中:
{% if 'ziqiangxuetang' in List %}
Django在名单中
{% endif %}
实例七,模板中 获取当前网址,当前用户等:
{% if request.user.is_authenticated %}
{{ request.user.username }},您好!
{% else %}
<a href="{{ request.path }}?{{ request.GET.urlencode }}&delete=1">当前网址加参数 delete</a>
{% endif %}