1.在应用目录下创建模板(templates目录)
在模板目录下创建archive.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Archive</title>
</head>
<body>
{% for post in posts%}
<h2>{{post.title}}</h2>
<p>{{post.timestamp}}</p>
<p>{{post.body}}</p>
{% endfor %}
</body>
</html>
2.创建URL模式
为了区别项目URL和应用URL,复合物代码重用、DRY等准则。通过两部步定义URL映射规则并创建两个URLconf:一个用于项目,一个用于应用。
项目urls.py:
from django.conf.urls import url
from django.contrib import admin admin.autodiscover() urlpatterns = [
url(r'^mysite/',include('myblog.urls')),
url(r'^admin/', admin.site.urls),
]
应用url.py:
from django.conf.urls import url
from .import views urlpatterns = [
url(r'^$',views.archive)
]
3.创建视图函数
from http.client import HTTPResponse from django.shortcuts import render, render_to_response # Create your views here.
from datetime import datetime
from django.template import loader, Context
from .models import BlogPost def archive(request):
posts = BlogPost.objects.all() '''
t = loader.get_template('archive.html')
c = Context({'posts': posts})
return HTTPResponse(t.render(c))
'''
return render_to_response('archive.html', {'posts':posts})
4.项目结构
5.数据库
6.测试
注意:配置templates及视图时:
编写views.py,其中返回index.html(默认在templates中寻找),不需要在settings.py中配置templates。