path()的参数:
(1)route:
是一串URL字符串,在处理请求时,Django会从urlpatterns的列表乡下查询,直到找到第一个与请求的URL匹配的path,在该模式下不检查浏览方式(get或是post等)和参数(默认参数,查询字符串等)
(2)views:
当Django找打匹配的模式时,他将使用HttpRequest对象作为第一个参数,并将URL中捕获的关键字参数来指定对应的views视图函数
(3)name:
命名URL
(4)kwargs:
可以在字典中将任意关键字参数传递个给视图函数
模版:
目前最知名最好用的是DTL(Django Templates Library)和jinjia2
Django是Python内置的模版语言,是一种带有特殊语法的HTML文件
(1)渲染模版文件:
1、通过render_to_string渲染模版(将HTML代码渲染成字符串)
导包:from django.templates.loeader import render_to_string
views视图函数:
def index_handler(request):
return HttpResponse(render_to_string(‘index.html’))
2、通过render渲染模版
导包:from django.shortcuts import render
views视图函数:
def index_handler(request):
return render(request, 'index.html')
(2)查找templates的路径配置(settings.py中):
BASE_DIR = os.path.dirname(os.pathabspath(__file__))
动态获取当前项目所在路径
Django会根据Settings.py中TEMPLATES下的DIRS所包含的路劲去寻找html的模版代码
如果DIRS为DIRS:[],则需要手动输入以下代码:
'DIRS': [os.path.join(BASIC_DIR, templates)]
或者Django会自动从已经激活的app中寻找templates文件
(此时必须开启APP_DIRS=True,否则Django将不会从任何app中寻找)
DTL模版传递参数:
通过render函数中的context来传递参数
views视图函数:
def index_handler(request):
context = {}
return render(request, ‘index.html’, context)
参数类型: 在模版中获取:
普通参数( {{ name }}
context={
'name': '罗贯中'
}
)
列表参数( {{ name.0 }}
context = { {{ name.1 }}
'name' = [
'罗贯中','吴承恩'
]
}
)
字典参数( {{ book.name }}
context={ {{ book.author }}
'book':{
'name':'三国演义',
'author':'罗贯中'
}
}
)
DTL模板标签:
1、autospace标签:
控制当前的自动转义行为,采用on或 off作为参数
views.py中的代码:
def autospace_handler(request):
context = {
‘first_list’: ‘百度’
}
return render(request, ‘index.html’, context=context)
html中的代码:
{% autoescape off %}
{{ first_list }}
{% endautoescape %}
获得效果: 百度
{% autoescape on %}
{{ first_list }}
{% endautoescape %}
获得效果: <a href="www.baidu.com">百度</a>
2、block标签:
3、comment标签:
忽略comment和endcomment之间的所有内容,插入可选注释解释为什么会忽略该代码片段。
views.py中的代码:
def autospace_handler(request):
context = {
'first_list': '<a href="www.baidu.com">百度</a>',
'first_date': '2020.7.10',
'second_date': '2020.8.15'
}
return render(request, 'index.html', context=context)
html中的代码:
{% comment 'plan cannel' %}
<p>the book comes out at {{ first_date }}</p>
{% endcomment %}
<p>the book comes out at {{ second_date }}</p>
注意:comment 标签不能嵌套。
4、csrf_token标签:
5、cycle标签:
每次遇到此标签时,都会产生其参数之一。
第一个参数在第一次遇到时产生,第二个参数在第二次遇到时产生,依此类推。一旦所有参数用尽,标记将循环到第一个参数并再次产生它。
views.py中的代码:
def autospace_handler(request):
context = {
'first_list': '<a href="www.baidu.com">百度</a>',
'first_date': '2020.7.10',
'second_date': '2020.8.15',
'book_name': ['三国演义', '水浒传', '西游记', '红楼梦', '西厢记'],
}
return render(request, 'index.html', context=context)
html中的代码:
{% for book in book_name %}
{{ book }}:${% cycle '99' '100' '101' %}
{% endfor %}
在某些情况下,您可能希望引用循环的当前值而不前进到下一个值。为此,只需使用“ as” 为标签命名
views.py中的代码:
def autospace_handler(request):
context = {
'first_list': '<a href="www.baidu.com">百度</a>',
'first_date': '2020.7.10',
'second_date': '2020.8.15',
'book_name': ['三国演义', '水浒传', '西游记', '红楼梦', '西厢记'],
}
return render(request, 'index.html', context=context)
html中的代码:
{% for book in book_name %}
{{ book }}:${% cycle '99' '100' '101' %}
{% endfor %}
<p>{{ book_name.0 }}:${% cycle '99' '100' '101' as book_price %}</p>
<p>{{ book_name.1 }}:${{ book_price }}</p>
<p>{{ book_name.2 }}:${% cycle book_price %}</p>
可以在cycle标签中使用任意数量的值,并用空格分隔。
用单引号(')或双引号(")括起来的值被视为字符串文字,而不带引号的值被视为模板变量。
默认情况下,将as关键字与cycle标签一起使用时,as将会获取周期中产生第一个值。
如果要在嵌套循环或包含的模板中使用该值,可能会出现问题。
如果只想声明周期而不产生第一个值,则可以在标签中添加一个slient关键字。
html中的代码:
{% cycle 'one' 'two' as numbers silent %}
{{ numbers }}
{% cycle numbers %}
在循环定义中使用silent关键字时,silent自动应用于该特定循环标记的所有后续使用。即使对{%cycle%}的第二次调用没有指定silent,以下模板也不会输出任何内容:
html中的代码(将以下两个断码片段运行一下就会知道):
{% cycle 'one' 'two' as numbers silent %}
{{ numbers }}
{% cycle numbers %}
{% cycle 'one' 'two' as numbers %}
{% cycle numbers %}
6、debug标签:
7、extend标签:
8、filter标签:
通过一个或多个过滤器过滤块的内容
html中的代码:
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in all lowercase.
<P>hello WORLD</P>
<a href="#">百度</a>
{% endfilter %}
9、firstof标签:
输出第一个值不是False的参数变量
如果所有传递的变量均为False,则不输出任何内容。
views.py中的代码:
def autospace_handler(request):
context = {
'first_list': '<a href="www.baidu.com">百度</a>',
'first_date': '2020.7.10',
'second_date': '2020.8.15',
'book_name': ['三国演义', '水浒传', '西游记', '红楼梦', '西厢记'],
'var': {
'first': '',
'second': '',
'third': "It is mine",
}
}
return render(request, 'index.html', context=context)
html中的代码:
{% firstof var.first var.second var.third %}
这等效于:
{% if var.first %}
{{ var.first }}
{% elif var.second %}
{{ var.second }}
{% elif var.third %}
{{ var.third }}
{% endif %}
如果所有传递的变量均为False,则还可以使用文字字符串作为后备值:
{% firstof var.first var.second var.third 'all is false' %}
10、for标签:
循环访问数组中的每个项目
views.py中的代码:
def autospace_handler(request):
context = {
'boos': [{
"book_name": '三国演义',
'author_name': '罗贯中',
'price': 99
}, {
"book_name": '水浒传',
'author_name': '施耐庵',
'price': 199
}, {
"book_name": '西游记',
'author_name': '吴承恩',
'price': 159
}, {
"book_name": '红楼梦',
'author_name': '曹雪芹',
'price': 59
},
]
}
return render(request, 'index.html', context=context)
html中的代码:
<table>
<thead>
<tr>
<th>序号</th>
<th>书名</th>
<th>作者</th>
<th>价格</th>
</tr>
</thead>
<tbody>
{% for book in boos %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.book_name }}</td>
<td>{{ book.author_name }}</td>
<td>{{ book.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
可以使用反向遍历列表,引入reversed关键字:
{% for obj in list reversed %}
如果给定数组为空或找不到,则{% empty %}标记可以带有一个可选子句,其文本显示出来:
{% for obj in list reversed %}
{% empty %}
{% endfor %}
变量 描述
forloop.counter 循环的当前迭代(1索引)
forloop.counter0 循环的当前迭代(0索引)
forloop.revcounter 从循环末尾开始的迭代次数(1索引)
forloop.revcounter0 从循环末尾开始的迭代次数(0索引)
forloop.first 如果这是第一次循环,则为真
forloop.last 如果这是最后一次循环,则为true
forloop.parentloop 对于嵌套循环,这是围绕当前循环的循环
11、if标签:
计算一个变量的值如是True(不为空),那么数据块的内容被输出:
html中的代码:
{% if var.first %}
<p>first choice</p>
{% elif var.second %}
<p>second choice</p>
{% else %}
<p>third choice</p>
{% endif %}
if标签可以使用not,and,or等布尔运算符,也可以使用==,!=,<,>, <=,>=,in等等
注意:
在if标记中使用括号是无效的语法
比较运算符不能像Python或数学符号那样被“链接”:
{% if a > b > c %}
也可以在if表达式中使用过滤器:
html中的代码:
{% if messages|length >= 100 %}
You have lots of messages today!
{% endif %}
12、ifequal和ifnotequal标签:
{% ifequal a b %} {% endifequal %}是一种过时的写作方式,由{% if a == b %}{% endif %}取代。
{% ifnotequal a b %} {% endifnotequal %}也是一种过时的写作方式,由{% if a != b %} {% endif %}取代。
13、ifchanged标签:
(1):检查循环的最近一次迭代是否更改了{% ifchanged %}{% endifchanged%}之间表达式的值
views.py中的代码:
def autospace_handler(request):
context = {
'dates': [{
'year': 2019,
'month': 1
}, {
'year': 2020,
'month': 1
}, {
'year': 2021,
'month': 1
}]
}
return render(request, 'index.html', context=context)
html中的代码:
{% for date in dates %}
{% ifchanged %}
{{ date.year }}
{% endifchanged %}
{{ date.month }}
{% endfor %}
(2)对于给定的一个或多个变量,检查是否有任何变量发生了变化:
views中的代码:
def autospace_handler(request):
context = {
'dates': [{
'year': 2019,
'month': 1,
'day': 20
}, {
'year': 2019,
'month': 2,
'day': 20
}, {
'year': 2021,
'month': 1,
'day': 20
}]
}
return render(request, 'index.html', context=context)
html中的代码:
{% for date in dates %}
{% ifchanged date.year %}
{{ date.year }}
{% endifchanged %}
{% ifchanged date.month %}
{{ date.month }}
{% endifchanged %}
{{ date.day }}
{% endfor %}
ifchanged标记还可以采用可选的{%else%}子句,如果值没有更改,则将显示该子句:
{% for date in dates %}
{% ifchanged date.year %}
{{ date.year }}
{% else %}
{{ date.year }}
{% endifchanged %}
{% ifchanged date.month %}
{{ date.month }}
{% endifchanged %}
{{ date.day }}
{% endfor %}
14、include标签:
views.py中的代码:
html中的代码:
15、load标签:
加载自定义模板标记集
例如以下模板将加载在位于包somelibrary和otherlibrary中注册的所有标记和筛选器:
{% load somelibrarypackage.otherlibrary%}
还可以使用from参数有选择地从库中加载单个过滤器或标记。
{%load foo bar from somelibrary%}
16、loorem标签:
显示随机的拉丁文文本:
{% lorem [count] [method] [random] %}
参数 说明
count 一个数字(或变量),包含要生成的段落或单词的数量(默认为1)
method w(word),p(HTML p)或b(binary 纯文本段落块)(默认为b)。
random random生成文本时,如果给出该词,则不使用公共段落(“ Lorem ipsum dolor sit amet…”)。
html中的代码:
{% lorem %}
<hr>
{% lorem 3 p %}
<hr>
{% lorem 2 w random %}
17、now标签:
使用根据给定字符串的格式显示当前日期和/或时间。这样的字符串可以包含格式说明符,如date过滤器部分所述
传递的格式也可以是下面表达式之一:
DATE_FORMAT,
DATETIME_FORMAT,
SHORT_DATE_FORMAT,
SHORT_DATETIME_FORMAT
html中的代码:
<p>{% now "DATE_FORMAT" %}</p>
<p>{% now "DATETIME_FORMAT" %}</p>
<p>{% now "SHORT_DATE_FORMAT" %}</p>
<p>{% now "SHORT_DATETIME_FORMAT" %}</p>
您还可以使用语法将输出(作为字符串)存储在变量内:
{% now "Y" as current_year %}
18、regroup标签:
通用属性将相似对象列表重新组合
regroup接受三个参数:list要重新分组的列表
confidence分组依据的属性
listname结果列表的名称
{% regroup list by confidence as listname %}
views.py中的代码:
def autospace_handler(request):
context = {
'cities': [
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]
}
return render(request, 'index.html', context=context)
html中的代码:
{% regroup cities by country as country_list %}
<ul>
{% for country in country_list %}
<li>{{ country.grouper }}
<ul>
{% for city in country.list %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
regroup生成组对象的列表有两个字段的实例:
grouper –分组的项目(confidence)
list –该组中所有项目的列表(detail data)
{% regroup cities by country as country_list %}
<ul>
{% for country, local_cities in country_list %}
<li>{{ country }}
<ul>
{% for city in local_cities %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
注意:
实际例子依赖于这样一个事实:
城市列表首先是按国家排序的。如果城市列表没有按国家对其成员进行排序,那么重新组合将天真地显示单个国家的多个组。
India
Mumbai: 19,000,000
USA
New York: 20,000,000
India
Calcutta: 15,000,000
USA
Chicago: 7,000,000
Japan
Tokyo: 33,000,000
所以在进行regoup时请保证你选用的字段是已经拍完序的(可以使用dictsort过滤器来进行排序):
{% regroup cities|dictsort:"country" by country as country_list %}
任何有效的模板字段查找都是重组标记的合法分组属性,包括方法、属性、字典键和列表项。
如果“country”字段是具有“description”属性的类的外键,则可以使用以下方式进行重新分组:
views.py中的代码:
def autospace_handler(request):
context = {
'cities': [
{'name': 'Mumbai', 'population': '19,000,000', 'country': {'name': 'India'}},
{'name': 'Calcutta', 'population': '15,000,000', 'country': {'name': 'India'}},
{'name': 'New York', 'population': '20,000,000', 'country': {'name': 'USA'}},
{'name': 'Chicago', 'population': '7,000,000', 'country': {'name': 'USA'}},
{'name': 'Tokyo', 'population': '33,000,000', 'country': {'name': 'Japan'}},
]
}
return render(request, 'index.html', context=context)
index.html中的代码:
{% regroup cities by country.name as country_list %}
<ul>
{% for country in country_list %}
<li>{{ country.grouper }}
<ul>
{% for city in country.list %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
{% regroup cities by country.name as country_list %}
<ul>
{% for country, local_cities in country_list %}
<li>{{ country }}
<ul>
{% for city in local_cities %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
如果country是带有的字段choices,它将有一个 get_country_display()方法可以用作属性,使您可以在显示字符串而不是choices键上分组
19、resetcycle标签:
重置上一个循环,以便在下一次遇到时从其第一项重新开始
views.py中的代码:
def autospace_handler(request):
context = {
'numbers': [1, 2, 3, 4],
'values': ['a', 'b', 'c']
}
return render(request, 'index.html', context=context)
html中的代码:
{% for number in numbers %}
{% for value in values %}
{% cycle 'old' 'new' as age silent %}
<p>{{ value }}:{{ age }}</p>
{% endfor %}
{% resetcycle %}
{% endfor %}
还可以重置命名循环标签
{% for number in numbers %}
{% for value in values %}
{% cycle 'old' 'new' as age silent %}
<p>{{ value }}:{{ age }}</p>
{% resetcycle age %}
{% endfor %}
{% endfor %}
20、spaceless标签:
删除HTML标记之间的空白字符(空格、制表符和换行符等)
html中的代码:
{% spaceless %}
<p>
I'am a boy
</p>
<br>
<h1>You're a girl</h1>
{% endspaceless %}
21、templatetag标签:
输出用于组成模板标签的语法字符之一
由于模板系统没有“转义”的概念,因此要显示模板标签中使用的位之一,必须使用标签
字符 输出
openblock {%
closeblock %}
openvariable {{
closevariable }}
openbrace {
closebrace }
opencomment {#
closecomment #}
html中的代码:
{% templatetag openblock %}
22、url标签:
返回与给定视图和可选参数匹配的绝对路径引用(不带域名的URL)
url反转传递关键字参数:
{% url '[<appname>:]<urlname>' arg(=value) %}
url反转传递查询字符串,在URL外手动添加查询字符串
{% url '[<appname>:]<urlname>'}?next=xxx
注意:
如果反转的URL不存在,NoReverseMatch则会引发异常,这将导致您的网站显示错误页面。
如果您想检索一个URL但不显示它,则可以使用一个稍微不同的调用:
{% url '[<appname>:]<urlname>' as othername %}
urls.py中的代码:
from django.urls import path
from . import views
app_name = 'user'
urlpatterns = [
path('', views.autospace_handler, name='autospace'),
path('search/', views.search_handler, name='search')
]
views.py中的代码:
def search_handler(request):
return render(request, 'search.html')
def autospace_handler(request):
context = {
'numbers': [1, 2, 3, 4],
'values': ['a', 'b', 'c']
}
return render(request, 'index.html', context=context)
index.html中的代码:
{% url 'user:search' arg arg2 as the_url %}
<a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
search.html中的代码:
<a href="https://www.baidu.com/">百度</a>
23、verbatim标签:
阻止模板引擎呈现此block标记的内容(关闭DTL默认解析特殊字符串的功能)
通常的用途是允许JavaScript模板层与Django的语法冲突
html中的代码:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
24、widthratio标签:
views.py中的代码:
def autospace_handler(request):
context = {
'numbers': [1, 2, 3, 4],
'values': ['a', 'b', 'c'],
'this_value': 175,
"max_value": 200,
"max_width": 100
}
return render(request, 'index.html', context=context)
html中的代码:
<img src="bar.png" alt="Bar" height="10" width="{% widthratio this_value max_value max_width %}">
需要手动传入this_value max_value max_width的值
{% widthratio this_value max_value max_width as width %}
计算方法:width=this_value/max_value*max_width
25、with标签:
再模版中定义变量
{% with var(=value) %}
或:{% with value as var %}
注意:
在var(变量名)和value(赋值)中间不需要加空格