AI智能
改变未来

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


学习资料

《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 MonthArchiveViewfrom index.models import PersonInfoclass IndexMonth(MonthArchiveView):allow_empty = Trueallow_futuread8= True# 查询的所得数据对象context_object_name = \'mylist\'template_name = \'index.html\'model = PersonInfodate_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 WeekArchiveViewfrom index.models import PersonInfoclass IndexWeek(WeekArchiveView):allow_empty = Trueallow_future = Truecontext_object_name = \'mylist\'template_name = \'index.html\'model = PersonInfodate_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>

启动项目访问效果如下

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 《Django Web应用开发实战》学习笔记 12- CBV(类视图)-日期筛选视图