A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 我是楠楠 黑马粉丝团   /  2017-12-15 10:31  /  2200 人查看  /  7 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

【郑州校区】Django 之----模版的使用

如果对Django基本配置还是小白的话,请移步:
第一:在setting中配置模版文件夹
My_Django/setting.py
[AppleScript] 纯文本查看 复制代码
 TEMPLATES = [ #模版
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')] # 模版文件夹
....

                ],

        },
    ]
第二:编写一个模版html
templates/hello/index.html
[AppleScript] 纯文本查看 复制代码
  <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{{ title }}</title>
    </head>
    <body>
        <ul>
            {% for item in list%}
            <li>{{ item }}</li>
            {% endfor %}
        </ul>
    </body>
    </html>
第三:使用视图函数返回模版
Django提供了一个函数render封装了以上代码 方法render包含3个参数
  • 第一个参数为request对象
  • 第二个参数为模板文件路径
  • 第三个参数为字典,表示向模板中传递的上下文数据
hello/views.py:
[AppleScript] 纯文本查看 复制代码
 from django.http import HttpResponse, request
        from django.shortcuts import render
            '''
            定义了一个试图函数
            requset : 请求的request
            '''
            def hello(request):
                # 传递给模板的数据
                context = {'title': '我是模板', 'list': range(10)}
                return render(request, 'hello/index.html', context)
                #return HttpResponse("你好,我是模块!")
访问http://127.0.0.1:8000/hello 效果如下:


传智播客·黑马程序员郑州校区地址
河南省郑州市 高新区长椿路11号大学科技园(西区)东门8号楼三层
联系电话 0371-56061160/61/62
来校路线  地铁一号线梧桐街站A口出

7 个回复

倒序浏览
学习学习
回复 使用道具 举报
回复 使用道具 举报
楼主赞一个
回复 使用道具 举报
回复 使用道具 举报
kankan
回复 使用道具 举报
6666666666666666666
回复 使用道具 举报
pysl 中级黑马 2018-7-29 11:14:08
8#
学习学习
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马