[Python]Django Step by Step 笔记(三)

这篇博客介绍了如何使用Django创建一个简单的通讯录应用,通过编写`list.py`视图函数,传递数据到`list.html`模板,然后在模板中使用for循环展示字典列表内容,形成一个两列的表格。读者可以了解到Django模板的基本语法,包括变量引用、属性访问以及for循环标签的使用。
摘要由CSDN通过智能技术生成
  1.  创建 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})

  2. 创建 templates 目录

  3. 创建 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}} 就是将字典中的元素取出来。

  4. 修改 settings.py:
    TEMPLATE_DIRS  =  (
        
    #  Put strings here, like "/home/html/django_templates".
         #  Always use forward slashes, even on Windows.
         ' ./templates ' ,
    )


  5. 修改 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')),
    )


  6. 启动web server, 测试地址:
    http://localhost:8000/list
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值