在前面的几节中咱们都是用简单的 django.http.HttpResponse 来把内容显示到网页上,本节将讲解如何使用渲染模板的方法来显示内容。html
一、在views里写一个首页的视图python
from django.shortcuts import render def home(request): return render(request, 'home.html')
二、templates 文件夹,里面新建一个 home.html数据库
三、将视图函数对应到网址,修改urls.py文件django
完成以上3步便可实现模板显示。服务器
四、建立数据库表app
python manage.py migrate
建立数据库虽然本节不会用到,可是可让一些提示消失(提示你要建立数据库之类的)函数
五、运行开发服务器,看看效果网站
python manage.py runserver
模板补充知识:url
网站模板的设计,通常的,咱们作网站有一些通用的部分,好比 导航,底部,访问统计代码等等spa
nav.html, bottom.html, tongji.html
能够写一个 base.html 来包含这些通用文件(include)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!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 其它的模板文件。
好比咱们的首页 home.html,继承或者说扩展(extends)原来的 base.html,能够简单这样写,重写部分代码(默认值的那一部分不用改)
1
2
3
4
5
6
7
8
|
{% 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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 模板进阶。