- 创建 list.py:
#
coding=utf-8
from
django.shortcuts
import
render_to_response
address
=
[
{
'
name
'
:
'
张三
'
,
'
address
'
:
'
地址一
'
},
{
'
name
'
:
'
李四
'
,
'
address
'
:
'
地址二
'
}
]
def
index(request):
return
render_to_response(
'
list.html
'
, {
'
address
'
: address})
- 创建 templates 目录
- 创建 list.html 文件:
<
meta
http-equiv
="Content-Type"
content
="text/html; charset=UTF-8"
/>

<
h2
>
通讯录
</
h2
>
<
table
border
="1"
>
<
tr
><
th
>
姓名
</
th
><
th
>
地址
</
th
></
tr
>
{%for user in address%}
<
tr
>
<
td
>
{{user.name}}
</
td
>
<
td
>
{{user.address}}
</
td
>
</
tr
>
{%endfor%}
</
table
>
很简单,就是这样生成一个两列的表格。
在Django的template中, {{}}表示引用一个变量, {%%}表示代码调用。
在变量引用中,Django支持对变量属性的访问,同时还有一定的策略,详细建议请查阅相关文档。
这里使用的 for...in 的模版 Tag 处理。 因此 address 需要是一个集合。 在我们 view(list.py) 的 代码中, adress 是一个 list. 每一个list又是一个字典, 因此, {{user.name}} 和 {{user.address}} 就是将字典中的元素取出来。 - 修改 settings.py:
TEMPLATE_DIRS
=
(
#
Put strings here, like "/home/html/django_templates".
#
Always use forward slashes, even on Windows.
'
./templates
'
,
)
- 修改 urls.py:
from
django.conf.urls.defaults
import
*

urlpatterns
=
patterns(
''
,
#
Example:
#
(r'^testit/', include('newtest.apps.foo.urls.foo')),
(r
'
^$
'
,
'
newtest.helloworld.index
'
),
(r
'
^add/$
'
,
'
newtest.add.index
'
),
(r
'
^list/$
'
,
'
newtest.list.index
'
),
#
Uncomment this for admin:
#
(r'^admin/', include('django.contrib.admin.urls')),
)
- 启动web server, 测试地址:
http://localhost:8000/list
[Python]Django Step by Step 笔记(三)
最新推荐文章于 2015-06-19 15:46:50 发布
这篇博客介绍了如何使用Django创建一个简单的通讯录应用,通过编写`list.py`视图函数,传递数据到`list.html`模板,然后在模板中使用for循环展示字典列表内容,形成一个两列的表格。读者可以了解到Django模板的基本语法,包括变量引用、属性访问以及for循环标签的使用。
490

被折叠的 条评论
为什么被折叠?



