参考追梦人物老师的博客记录的学习过程
本期以归档为例,实现点击不同的归档日期,调转到只包含对应日期的文章列表的首页。
模板页面_archives.html文件下,新增a标签,标签的url对应为处理该需求的试图函数。
href="{% url ‘blog:archives’ date.year date.month %}"通过{% url %}模板标签获得一个URL;
其中{% url %}为解析视图函数的url的模板标签。
- 它接受多个参数,第一个为要解析的视图函数的端点值,使用 'app_name:别名’方式标识;
- 其余参数为URL的路径参数,如日期中的year或month。
当点击a标签后网页跳转到对应的视图函数。
根据模板中的url要求,在blog/urls.py中定义URL规则。
from django.urls import path
from . import views
app_name = 'blog' # 告诉程序,当前的url模块属于哪个应用,此次是blog应用 --- 试图函数命名空间
urlpatterns = [
path('', views.index, name='index'),
path('posts//', views.detail, name='detail'),
path('archives///', views.archives, name='archives'),
path('category//', views.category, name='category'),
path('tag//', views.tag, name='tag')
]
对name=‘archives’ 该URL定义了访问路径,并指定了两个int类型的参数year,month。该路径指向views.archives视图函数。
编写archives视图函数根据逻辑要求,archives视图函数接受年月两个参数,并返回属于该日期下的所有文章,最后传递给index.html进行渲染。
blog/views.py
def archives(request,year,month):
"""
根据创建年月查询文章列表
"""
post_list = Post.objects.filter(
created_time__year = year,
created_time__month = month,
).order_by('-created_time')
return render(request, "blog/index.html", context={"post_list":post_list})
其中 Post.objects.filter()方法接受条件参数并返回满足条件的所以对象。
注意:方法中表示属性关系使用双下线 __ 而不是点 .;
如created_time__year表示created_time对象的year属性。
最终,当我们在网页中点击归档下的某一个日期时,模板根据该日期解析得到对应的视图函数,并将year、month参数传递过去。
archives方法接受这两个参数,并查询满足条件的文章列表,将其传递给index.html模板。渲染后呈现出来。
对于分类和标签板块,同样的方法。
如上图所示,呈现出不同类别下文章的数量。
以分类为例。
blog/modess.py文件下,对Category模型在新增get_count方法,返回类别为当前类别时,文章的数量。
class Category(models.Model):
"""
blog的分类的模型
"""
...
def get_count(self):
"""
返回当前分类下的文章数量
"""
posts = Post.objects.filter(category=self)
return len(posts)
...
于是在templatesbloginclusions_archives.html中,可以使用category.get_count获取不同类别的文章数量。
...
{% for category in category_list %}



