一、配置路由
from django.urls import path,re_path
from . import views
urlpatterns=[
re_path('^$',views.IndexView.as_view(),name='index'),
re_path('^list/(?P<channel_id>\d+)/(?P<page_num>\d+)/$',views.IndexView.as_view())
]
二、完善视图
from django.shortcuts import render
from django.views.generic.base import View
# Create your views here.
from .models import NewsChannel, Article
from django import http
from django.core.paginator import Paginator, EmptyPage
class IndexView(View):
def get(self,request,channel_id=1,page_num=1):
'''
新闻列表展示功能
:param request:
:return:
'''
#获取频道对象
try:
newschannel=NewsChannel.objects.get(id=channel_id)
except NewsChannel.DoseNotExist:
return http.HttpResponseNotFound('未找到channel_id')
else:
#获取当前频道下的所有类别id
category_id_list=[category.id for category in newschannel.newscategory_set.all() if category]
#查询当前频道下的所有文章
articles=Article.objects.filter(category_id__in=category_id_list).order_by('id')
#创建分页器对象
page_obj=Paginator(articles,3)
#获取当前页数据
try:
page_articles=page_obj.page(page_num)
except EmptyPage:
return http.HttpResponseNotFound('未找到相应page_num')
return render(request,'newsapp/index.html',{'articles':page_articles,'channel_id':channel_id})
三、编辑newsapp/index.html
新闻列表部分
<div class="site-main">
<h3 class="custom_blog_title">
新闻列表
</h3>
<div class="blog-list list-style">
{% for article in articles %}
<div class="blog-item">
<div class="post-format">
<a href="#">
<img src="{{ article.default_img.url }}" alt="img">
</a>
</div>
<div class="post-info">
<div class="category-blog">
<a href="#">{{ article.category.name }}</a>
</div>
<h3 class="post-title">
<a href="#">{{ article.title }} </a>
</h3>
<div class="author-view">
<div class="author">
<div class="avt">
<img src="/static/images/avt-blog1.png" alt="img">
</div>
<h3 class="name">
设计本本
</h3>
</div>
<div class="review">
<div class="view">
<span class="icon-view">
<i class="fa fa-eye" aria-hidden="true"></i>
</span>
<span class="count">
631
</span>
</div>
<div class="s-comments">
<span class="icon-cmt">
<i class="fa fa-commenting" aria-hidden="true"></i>
</span>
<span class="count">
82
</span>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
分⻚部分
<div class="pagination clearfix style2">
<div class="nav-link">
{% if articles.has_previous() %}
<a href="/list/{{ channel_id }}/{{ articles.number - 1 }}/" class="page-numbers"><i class="icon fa fa-angle-left" aria-hidden="true"></i></a>
{% endif %}
{% for num in range(1,articles.paginator.num_pages + 1) %}
<a href="/list/{{ channel_id }}/{{ num }}/" class="page-numbers {% if num == articles.number %}current{% endif %}">{{ num }}</a>
{% endfor %}
{% if articles.has_next() %}
<a href="/list/{{ channel_id }}/{{ articles.number + 1 }}/" class="page-numbers"><i class="icon fa fa-angle-right" aria-hidden="true"></i></a>
{% endif %}
</div>
</div>