Django学习(三)定制情书
2017-12-08 本文已影响29人
山阴少年
在Django学习(一)一首情诗中,views.py中HTML被直接硬编码在代码之中,虽然这样便于解释视图是如何工作的,但直接将HTML硬编码到视图却不算一个好主意。因为:
- 对页面设计进行的任何改变都必须对Python代码进行相应的修改,而站点设计的修改往往比底层Python代码的修改要频繁得多。
- Python代码编写和HTML设计是两项不同的工作,大多数专业的网站开发环境都将它们分配给不同的人员来完成。
- 程序员编写Python代码和设计人员制作模板两项工作同时进行的效率是最高的,远胜于让一个人等待另一个人完成对某个既包含Python又包含HTML的文件的编辑工作。
基于以上原因,Django推荐使用模板。模板(Template)是一个文本,用于分离文档的表现形式和内容。模板通常用于产生HTML.
本次分享的目标是利用Django的模板来产生一封简单的情书。这需要用到Django模板方面的知识。
先新建项目love_letter:
django-admin.py startproject love_letter
切换到该文件夹下的love_letter目录,新建letter.html文件,即Django的模板,代码如下:
<html>
<head>
<title>Love Letter</title>
</head>
<body>
<h1>Love Letter for {{ name }}</h1>
<p>Dear {{ name }}:</p>
<p>Now you are reading a letter from your BF. Thanks for reading it.</p>
<p>We met on {{met_date}}, and today is {{today}}, so we have been together for {{days}} days.</p>
<p>Now you live in {{your_city}}, and I live in {{my_city}}.
{% ifequal your_city.lower my_city.lower %}
So lucky for living in the same city!
{% else %}
What a pity for not being together!
{% endifequal %}
</p>
<p>So glad to meet you! You must be the heaven-sent angel for you are
<ul>
{% for trait in traits %}
<li>{{trait}}</li>
{% endfor %}
</ul>
I'm so fascinated of you!
</p>
<p>
It is now {{weather}} in {{your_city}},
{% ifequal weather 'cold'%}
take care of yourself.
{% else %}
{% ifequal weather 'hot'%}
take care of yourself.
{% else %}
nice weather, isn't it?
{% endifequal %}
{% endifequal %}
Hoping for seeing you soon! May you have a pleasent day!
</p>
<p>Yours Sincerely,<br/>{{ today }}<br/>{{ author }}</p>
</body>
</html>
我们有必要对这个模板做解释:
- {{ name }}表示name变量,所有{{...}}里面包含的是变量。
- {% ifequal your_city.lower my_city.lower %}为标签(tag),表示if判断语句,判断两个变量是否相等,需要用{% endifequal %}来结束。
- {% for trait in traits %}为标签,表示for循环语句,traits可以为list或者set序列,需要用{% endfor %}。
- 其余代码同HTML相同
定义好模板之后,我们应该告诉Django怎样使用这个模板,因此,需要在settings.py中的TEMPLATES设置DIRS:

这样我们就能在视图中使用该模板了。在相同的文件夹下,新建views.py,代码如下:
from django.shortcuts import render_to_response
import datetime
def output(request):
c = {'name':'Rose',
'met_date': datetime.datetime(2016,5,24,18,0,0),
'today': datetime.datetime.now(),
'your_city': 'shanghai',
'my_city': 'Shanghai',
'traits': ['young and pretty', 'lovely and positive', 'warm-hearted and careful', 'independent and clever'],
'weather': 'cold',
'author': 'Jclian'
}
c['days'] = (c['today'] - c['met_date']).days
return render_to_response('letter.html', c)
其中c为字典,keys为模板中定义的变量,values可以自由定义。
最后配置好urls.py,并开启8000端口,在网页中输入localhost:8000,得到的页面如下:

参考文献:
- Django中文教程.pdf:http://download.csdn.net/download/huangzhichang13/8177581
- Django官方文档之Templates:https://docs.djangoproject.com/en/2.0/topics/templates/