模板中通过双层for循环实现栏目页的列表和文章有序调用
1.HTML页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Python教程 - Python自学网</title>
</head>
<body>
<h1>标题</h1>
<h2>第1章:python进阶教程</h2>
<ol>
<li><a href="#" title="python变量">第1课:python变量</a></li>
<li><a href="#" title="python变量">第2课:python变量</a></li>
<li><a href="#" title="python变量">第3课:python变量</a></li>
</ol>
<h2>第2章:python进阶教程</h2>
<ol>
<li><a href="#" title="python变量">第1课:python变量</a></li>
<li><a href="#" title="python变量">第2课:python变量</a></li>
<li><a href="#" title="python变量">第3课:python变量</a></li>
</ol>
<h2>第3章:python进阶教程</h2>
<ol>
<li><a href="#" title="python变量">第1课:python变量</a></li>
<li><a href="#" title="python变量">第2课:python变量</a></li>
<li><a href="#" title="python变量">第3课:python变量</a></li>
</ol>
</body>
</html>
2.路由:
from django.urls import re_path, path
from . import views
urlpatterns = [
re_path(r'^$', views.index),
re_path(r'^blog/$', views.blog), # 列表页
re_path(r'^(\w+)/$', views.article), # 内容页
re_path(r'^django.html$', views.django), # 栏目页
]
3.视图:
# 内容页
def article(request, name):
art = Article.objects.get(art_tail=name)
context = {'art': art}
return render(request, 'test2.html', context=context)
# 列表页
def blog(request, name):
list = Article_List.objects.get(art_list_tail=name)
arts = Article.objects.filter(art_top_list__art_list_tail=name)
context = {'list': list, 'arts': arts}
return render(request, 'test4.html', context=context)
# 栏目页
def django(request, name):
col = Article_Col.objects.get(art_col_tail=name)
lists = Article_List.objects.filter(art_top_col__art_col_tail=name).order_by('art_list_click')
context = {'col': col, 'lists': lists}
return render(request, 'test5.html', context=context)
# 最终模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ col.art_col_title }} - Python自学网</title>
</head>
<body>
<!-- -->
<h1>{{ col.art_col_title }}</h1>
{% for list in lists %}
<h2>第{{ forloop.counter }}章:{{ list.art_list_title }}</h2>
<ol>
{% for art in list.article_set.all|dictsort:"art_time" %}
<li><a href="/art_{{art.art_tail}}/" title="{{ art.art_title }}">第{{ forloop.counter }}课:{{ art.art_title }}</a></li>
{% endfor %}
</ol>
{% endfor %}
</body>
</html>