您的位置:首页 > 编程语言 > Go语言

《Django Web应用开发实战》学习笔记 12- CBV(类视图)-日期筛选视图

2020-11-10 23:05 671 查看

学习资料

《Django Web应用开发实战》

1. 日期筛选视图

日期筛选视图是根据模型里的某个日期字段进行数据筛选的,然后将符合结果的数据以一定的形式显示在网页上

2. 月份视图 MonthArchiveView

在index/models.py中修改如下

from django.db import models

# Create your models here.

class PersonInfo(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
age = models.IntegerField()
hireDate = models.DateField()

删除migrations db.sqlite3,启动Django项目

执行生成迁移文件命令

python manage.py makemigrations
,执行生成数据表命令
python manage.py migrate

在index/urls.py中添加下面路由

path('<int:year>/<int:month>.html', views.IndexMonth.as_view(), name='index_month')

在index/views.py添加下面视图

from django.views.generic import MonthArchiveView

from index.models import PersonInfo
class IndexMonth(MonthArchiveView):
allow_empty = True
allow_future
ad8
= True
# 查询的所得数据对象
context_object_name = 'mylist'
template_name = 'index.html'
model = PersonInfo
date_field = 'hireDate'
queryset = PersonInfo.objects.all()
year_format = '%Y'
month_format = '%m'
# 分页
paginate_by = 50

templates/index.html修改如下

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<ul>
{% for v in mylist %}
<li>{{ v.hireDate }}: {{ v.name }}</li>
{% endfor %}
</ul>
<p>
{# 计算上个月的日期 #}
{% if previous_month %}
Previous Month: {{ previous_month }}
{% endif %}
<br>
{# 计算下个月的日期 #}
{% if next_month %}
Next Month: {{ next_month }}
{% endif %}
</p>
</body>
</html>

启动项目访问效果如下

3. 周期视图 WeekArchiveView

index/urls.py中代码如下

path('<int:year>/<int:week>.html', views.IndexWeek.as_view(), name='index_week')

index/views.py添加如下视图

from django.views.generic import WeekArchiveView

from index.models import PersonInfo
class IndexWeek(WeekArchiveView):
allow_empty = True
allow_future = True
context_object_name = 'mylist'
template_name = 'index.html'
model = PersonInfo
date_field = 'hireDate'
queryset = PersonInfo.objects.all()
year_format = '%Y'
week_format = '%W'
paginate_by = 50

templates/index.html修改如下

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<ul>
{% for v in mylist %}
<li>{{ v.hireDate }}: {{ v.name }}</li>
{% endfor %}
</ul>
<p>
{% if previous_week %}
Previous Week: {{ previous_week }}
{% endif %}
<br>
{% if next_week %}
Next Week: {{ next_week }}
{% endif %}
</p>
</body>
</html>

启动项目访问效果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: