上一次用的是在视图中直接灌html代码,这个方法可以用,但显然并不合理,那个只是用来演示下django的工作原理,只是个过度阶段。
今天要讲的是在视图中使用模板,关于模板中的标签,前面已有讲过了
首先我们要创建一个用来存放模板的目录,我这里就用template命名了,记住目录路径,我这里使用绝对路径/home/user/.../template,中间根据自己的实际情况来填
然后还需要把它告诉django,好让django知道到哪里去找。
设置项目目录下的settings.py文件
里面有一个配置项,里面只有注释没有实际内容,将之前的目录放进去
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/user/.../template',
)
值得注意的是后面有一个‘,’
下面写下我们的模板,这里我用的是html,其实也可以是其他文件,自己随意。
<html>
<head><title>Ordering notice</title></head>
<body>
<h1>Ordering notice</h1>
<p>Dear {{ person_name }},</p>
<p>Thanks for placing an order from {{ company }}. It's scheduled to
ship on {{ ship_date|date:"F j, Y" }}.</p>
<p>Here are the items you've ordered:</p>
<ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% if ordered_warranty %}
<p>Your warranty information will be included in the packaging.</p>
{% else %}
<p>You didn't order a warranty, so you're on your own whenthe products inevitably stop working.</p>
{% endif %}
<p>Sincerely,<br />{{ company }}</p>
</body>
</html>
大概就是这个意思,关于标签之前已经说过了。
然后是视图函数,应该还记得这个是什么东西吧,不知道的可以看下前面的文章。
之前存放视图函数的是views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
import datetime
def hello(request):
return HttpResponse("hello world")
def showtime(request):
now = datetime.datetime.now()
html = "<html><body>It is now "+str(now)+"</body></html>"
return HttpResponse(html)
def letter(request):
name = "wang"
company = "kuxu"
date = datetime.datetime.now()
item = ["abcd","dbdkj"]
ordered_warranty = True
return render_to_response('letter.html',{
'person_name':name,
'company':company,
'ship_date':date,
'item_list':item,
'ordered_warranty':ordered_warranty})
这里添加视图函数letter
最后用到方法render_to_response起到了灌数据和渲染的作用
最后建立url与视图函数的映射,设置urls.py文件
from django.conf.urls import patterns, include, url
from mysite.views import hello,showtime,letter
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
('^hello/$',hello),
('^time/$',showtime),
('^letter',letter),
)
这样就可以了。不过要记得把导入函数的路径设置为自己的。