python Django 学习笔记(三)—— 模版的使用
模版基本介绍
模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。
来一个项目说明
1,建立MyDjangoSite项目具体不多说,参考前面。
2,在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版。
3,在刚建立的模版下建模版文件user_info.html
<html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>用户信息</title>
<head></head>
<body>
<h3>用户信息:</h3>
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
</body>
</html>
说明:{{ name }}叫做模版变量;{% if xx %} ,{% for x in list %}模版标签。
4,修改settings.py 中的TEMPLATE_DIRS
- 导入import os.path
- 添加 os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
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. #"E:/workspace/pythonworkspace/MyDjangoSite/MyDjangoSite/templates",
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
说明:指定模版加载路径。其中os.path.dirname(__file__)为当前settings.py的文件路径,再连接上templates路径。
5,新建视图文件views.py
#vim: set fileencoding=utf-8: #from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response def user_info(request):
name = 'zbw'
age = 24
#t = get_template('user_info.html')
#html = t.render(Context(locals()))
#return HttpResponse(html)
return render_to_response('user_info.html',locals())
说明:Django模板系统的基本规则: 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。
可以看到上面代码中注释部分
#t = get_template('user_info.html')
#html = t.render(Context(locals()))
#return HttpResponse(html)
get_template('user_info.html'),使用了函数 django.template.loader.get_template() ,而不是手动从文件系统加载模板。 该 get_template() 函数以模板名称为参数,在文件系统中找出模块的位置,打开文件并返回一个编译好的 Template 对象。
render(Context(locals()))方法接收传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。其中Context(locals())等价于Context({'name':'zbw','age':24}) ,locals()它返回的字典对所有局部变量的名称与值进行映射。
render_to_response Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。
6,修改urls.py
from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info # Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MyDjangoSite.views.home', name='home'),
# url(r'^MyDjangoSite/', include('MyDjangoSite.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)), url(r'^u/$',user_info), )
7,启动开发服务器
基本一个简单的模版应用就完成,启动服务看效果!
效果如图:
模版的继承
减少重复编写相同代码,以及降低维护成本。直接看应用。
1,新建/templates/base.html
<html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>{% block title %}{% endblock %}</title>
<head></head>
<body>
<h3>{% block headTitle %}{% endblock %}</h3>
{% block content %} {% endblock %} {% block footer %}
<h3>嘿,这是继承了模版</h3>
{% endblock%}
</body>
</html>
2,修改/template/user_info.html,以及新建product_info.html
urser_info.html
{% extends "base.html" %} {% block title %}用户信息{% endblock %} <h3>{% block headTitle %}用户信息:{% endblock %}</h3> {% block content %}
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
{% endblock %}
product_info.html
{% extends "base.html" %} {% block title %}产品信息{% endblock %} <h3>{% block headTitle %}产品信息:{% endblock %}</h3> {% block content %}
{{productName}}
{% endblock %}
3,编写视图逻辑,修改views.py
#vim: set fileencoding=utf-8: #from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response def user_info(request):
name = 'zbw'
age = 24
#t = get_template('user_info.html')
#html = t.render(Context(locals()))
#return HttpResponse(html)
return render_to_response('user_info.html',locals()) def product_info(request):
productName = '阿莫西林胶囊'
return render_to_response('product_info.html',{'productName':productName})
4,修改urls.py
from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info,product_info # Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MyDjangoSite.views.home', name='home'),
# url(r'^MyDjangoSite/', include('MyDjangoSite.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)), url(r'^u/$',user_info),
url(r'^p/$',product_info),
)
5,启动服务效果如下:
python Django 学习笔记(三)—— 模版的使用的更多相关文章
- 【原】Learning Spark (Python版) 学习笔记(三)----工作原理、调优与Spark SQL
周末的任务是更新Learning Spark系列第三篇,以为自己写不完了,但为了改正拖延症,还是得完成给自己定的任务啊 = =.这三章主要讲Spark的运行过程(本地+集群),性能调优以及Spark ...
- python Django 学习笔记(一)—— Django安装
注:本人python版本2.7.5 ,win7系统 安装Django https://www.djangoproject.com/download/ 官方下载Django-1.5.5.tar.gz 1 ...
- python Django 学习笔记(二)—— 一个简单的网页
1,创建一个django项目 使用django-admin.py startproject MyDjangoSite 参考这里 2,建立视图 from django.http import HttpR ...
- Python——Django学习笔记
Django——一个封装好的神奇框架 若本文有任何内容错误,望各位大佬指出批评,并请直接联系作者修改,谢谢!小白学习不易. 一.简要模型 模型类操作数据表: python manage.py shel ...
- Python & Django 学习笔记
最近在学校Python和Django.在学习中遇到了种种的问题,对于一个新手来说,下面的问题可能都会遇到.希望能帮助到那些和我一样的人!!0.python-dev安装(ubuntu) apt-get ...
- python Django 学习笔记(六)—— 写一个简单blog做增删改练手
简单效果图 1,创建一个项目myblog 可参考这里 myblog/ manage.py myblog/ __init__.py settings.py urls.py wsgi.py 2,创建blo ...
- python Django 学习笔记(五)—— Django admin自动管理界面
1,激活管理界面 修改settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.c ...
- python Django 学习笔记(四)—— 使用MySQL数据库
1,下载安装MySQLdb类库 http://www.djangoproject.com/r/python-mysql/ 2,修改settings.py 配置数据属性 DATABASES = { 'd ...
- Python——追加学习笔记(三)
错误与异常 AttributeError:尝试访问未知的对象属性 eg. >>> class myClass(object): ... pass ... >>> m ...
随机推荐
- OC基础(8)
自定义代码段 实例变量修饰符 依赖关系 *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bott ...
- 【LeetCode】17. Letter Combinations of a Phone Number
题目: 思路:设置两个List,一个存储当前层,一个存储最终层 public class Solution { public List<String> letterCombinations ...
- 【测试】并使用scott用户下的emp表写一条SQL语句,执行计划走唯一索引
SQL; SAL ---------- Execution Plan ---------------------------------------------------------- ------ ...
- 不能读取文件“itunes.library.itl”因为它是由更高级别的itunes所创建的
转自:https://zhidao.baidu.com/question/80796363.html 是因为你安装过高版本的后又装你版本的itunes. 你在电脑上搜索所有硬盘上的itunes lib ...
- yii中modules的命名规则
如上图,views下面的文件夹名全小写(否则会出现找不到相应视图的错误),Module文件名称第一个单词首字母大写. 总之,按照上面的格式就不会有错了~
- 学习练习 java20160507作业
第一题 求水仙花的个数: //求水仙花数 int zongshu = 0; for(int i =100; i<=999;i++) { int bai = i/100; //求百位上面的数字 i ...
- jar包程序 读取properties文件
String proFilePath = System.getProperty("user.dir") + "\\Mysettings.properties"; ...
- log4
<?xml version="1.0"?> <configuration> <configSections> <section name= ...
- (转)各种排序算法的分析及java实现
转自:http://www.cnblogs.com/liuling/p/2013-7-24-01.html 排序一直以来都是让我很头疼的事,以前上<数据结构>打酱油去了,整个学期下来才勉强 ...
- java servlet上传文件并把文件内容显示在网页中
servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象.下面我 ...