文章目录
一、任务
- 侧边栏的归档,分类,标签云点击显示相应内容
二、步骤
- views.py 中写查看分类的方法
- blog/urls.py 中配置访问路径
- 在对应的分类标签中填写正确的访问路径
三、代码
blog/views.py
def archive(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})
def category(request, pk):
cate = get_object_or_404(Category, pk=pk)
post_list = Post.objects.filter(category=cate).order_by("-created_time")
return render(request, 'blog/index.html', context={'post_list': post_list})
def tag(request, pk):
tag = get_object_or_404(Tag, pk=pk)
post_list = Post.objects.filter(tags=tag).order_by("-created_time")
return render(request, 'blog/index.html', context={'post_list': post_list})
blog/urls.py
path('blog/archives/<int:year>/<int:month>/', views.archive, name='archive'),
path('blog/categories/<int:pk>/', views.category, name='category'),
path('blog/tags/<int:pk>/', views.tag, name='tag'),
templates/blog/inclusions/_archives.html, _categories.html, _tags.html
<a href="{% url 'blog:archive' date.year date.month %}">{{ date.year }} {{ date.month }}</a>
<a href="{% url 'blog:category' category.id %}">{{ category.name }} <span class="post-count">(13)</span></a>
<a href="{% url 'blog:tag' tag.pk %}">{{ tag.name }}</a>
四、问题
- django 中 path的末尾的/加不加什么区别?
- blog 的 url 配置前面加不加blog呢?
附上 Gitee 地址:https://gitee.com/langxing/HelloDjango-blog-tutorial