动态的url的设置:
例1:r'^hello/\d+/$':其中\d+表示一位或多位数字,即这个URL模式将匹配类似/time/plus/2/ ,/time/plus/25/ ,甚至/time/plus/100000000000/ 的任何URL。
例2:r'^hello/(\d+)/$':将部分url内容作为实参传入相应的试图函数,其中‘()’表示的是从正则表达式中提取文本内容。
同理,‘()’不仅用来提取变量,也可用来提取url中的不变内容: url(r'^(time)/$',playTime),不过这没什么实际用途。
对应的函数如下:
def playTime(request,str):
now=datetime.datetime.now()
#html='<html><body>the current time is %s</body></html>'% now
return HttpResponse(str)
运行结果如下:
:
模板标签的使用:
①:if/else
a.在if表达式中,不同的逻辑连接次不能组合使用:
如 {% if a and b or c%}是不允许的,系统也不支持用圆括号来确定优先级
b.同一连接词可以多次使用,
c.if/else可以嵌套使用,
d.没有 {%elif%} 标签。
e.每个标签必须要用{% endif%}结束
②:{% for %}{%endfor%}
a).可以嵌套使用
b).’break‘ and 'continue' can't be used
c) .a default varibe:forloop
forloop.counter
forloop.counter0
forloop.revcounter
forloop.first:bool
forloop.last:bool
forloop.parentloop:point to the parent forloop
③:ifequal/ifnotequal
a) support the {%else%}
b) only variable,string,integer and float can be used;
bool,dictionary,list banned
④:注释
单行 {#。。。。。。#}
多行:
{%comment%}
.....
.......
{% endcomment %}
⑤:过滤器
用来变量在显示之前对其进行修改
如 {{name|upper}}:将那么转换为大写显示
如何使用模版文件:
首先在settings.py的TEMPLATE_DIR设置模版的位置,使用绝对路径时,要用/,而不是\,否则将出现模版服无法法找到的异常:TemplateNotFound
最简单的一种:
from django.shortcuts import render_to_response
render_to_response('template name/path',tuple),该方法返回一个HttpResponse对象
其中tuple可以用locals()函数代替,该方法返回当前试图函数中的所有变量和其对应的值的一个字典
模板的继承:
父模板中用{%block blockName%}{%endblock%}来标记可能要重载的部分
子模板第一句用{% extends '父模板的全名'%}表示继承的父模板,然后在自定义相应的块的内容:
格式:
{% block bloackname%}
。。。。。。。。
{%endblock%}