在manage.py所在的目錄創(chuàng)建一個(gè)名為 templates的新文件夾:
myproject/
|-- myproject/
| |-- boards/
| |-- myproject/
| |-- templates/ <-- 這里
| +-- manage.py
在templates文件夾中,創(chuàng)建一個(gè)名為home.html的HTML文件:
templates/home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Boards</title>
</head>
<body>
<h1>Boards</h1>
{% for board in boards %}
{{ board.name }} <br>
{% endfor %}
</body>
</html>
在上面的例子中,我們混入了原始HTML和一些特殊標(biāo)簽 {% for ... in ... %} 和 {{ variable }} 。它們是Django模板語(yǔ)言的一部分。上面的例子展示了如何使用 for遍歷列表對(duì)象。{{ board.name }}會(huì)在 HTML 模板中會(huì)被渲染成版塊的名稱,最后生成動(dòng)態(tài)HTML文檔。
在我們可以使用這個(gè)HTML頁(yè)面之前,我們必須告訴Django在哪里可以找到我們應(yīng)用程序的模板。
打開myproject目錄下面的settings.py文件,搜索TEMPLATES變量,并設(shè)置DIRS 的值為 os.path.join(BASE_DIR, 'templates'):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
本質(zhì)上,剛添加的這一行所做的事情就是找到項(xiàng)目的完整路徑并在后面附加“/templates”
我們可以使用Python shell進(jìn)行調(diào)試:
python manage.py shell
from django.conf import settings
settings.BASE_DIR
'/Users/vitorfs/Development/myproject'
import os
os.path.join(settings.BASE_DIR, 'templates')
'/Users/vitorfs/Development/myproject/templates'
看到了嗎?它只是指向我們?cè)谇懊娌襟E中創(chuàng)建的templates文件夾。
現(xiàn)在我們可以更新home視圖:
boards/views.py
from django.shortcuts import render
from .models import Board
def home(request):
boards = Board.objects.all()
return render(request, 'home.html', {'boards': boards})
生成的HTML:

我們可以用一個(gè)更漂亮的表格來(lái)替換,改進(jìn)HTML模板:
templates/home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Boards</title>
</head>
<body>
<h1>Boards</h1>
<table border="1">
<thead>
<tr>
<th>Board</th>
<th>Posts</th>
<th>Topics</th>
<th>Last Post</th>
</tr>
</thead>
<tbody>
{% for board in boards %}
<tr>
<td>
{{ board.name }}<br>
<small style="color: #888">{{ board.description }}</small>
</td>
<td>0</td>
<td>0</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

原文:https://github.com/pythonzhichan/django-beginners-guide/blob/master/Fundamentals-3-1.md