Python Web开发:"新闻列表"后台处理函数
来自CloudWiki
技术原理
“新闻”模块整体访问流程:
1) 用户单击“企业要闻”“行业新闻”“通知公告”任一子页面产生请求,通过浏览器将请求发送至服务器
2)服务器采用统一的路由进行映射,匹配指定的视图函数进行处理
3)视图函数根据请求附带的参数来确定请求的子页面类型,通过ORM操作来过滤、查询数据并返回页面
4)前端收到返回的页面内容进行输出,其中富文本内容按照编辑时的样式进行渲染
实训步骤
编写视图处理函数=
newsApp/views.py:
from django.shortcuts import render from .models import MyNew from django.core.paginator import Paginator from django.shortcuts import get_object_or_404 from pyquery import PyQuery as pq def news(request, newName): # 解析请求的新闻类型 submenu = newName if newName == 'company': newName = '企业要闻' elif newName == 'industry': newName = '行业新闻' else: newName = '通知公告' # 从数据库获取、过滤和排序数据 newList = MyNew.objects.all().filter( newType=newName).order_by('-publishDate') for mynew in newList: html = pq(mynew.description) # 使用pq方法解析html内容 mynew.mytxt = pq(html)('p').text() # 截取html段落文字 # 分页 p = Paginator(newList, 5) if p.num_pages <= 1: pageData = '' else: page = int(request.GET.get('page', 1)) newList = p.page(page) left = [] right = [] left_has_more = False right_has_more = False first = False last = False total_pages = p.num_pages page_range = p.page_range if page == 1: right = page_range[page:page + 2] print(total_pages) if right[-1] < total_pages - 1: right_has_more = True if right[-1] < total_pages: last = True elif page == total_pages: left = page_range[(page - 3) if (page - 3) > 0 else 0:page - 1] if left[0] > 2: left_has_more = True if left[0] > 1: first = True else: left = page_range[(page - 3) if (page - 3) > 0 else 0:page - 1] right = page_range[page:page + 2] if left[0] > 2: left_has_more = True if left[0] > 1: first = True if right[-1] < total_pages - 1: right_has_more = True if right[-1] < total_pages: last = True pageData = { 'left': left, 'right': right, 'left_has_more': left_has_more, 'right_has_more': right_has_more, 'first': first, 'last': last, 'total_pages': total_pages, 'page': page, } return render( request, 'newList.html', { 'active_menu': 'news', 'sub_menu': submenu, 'newName': newName, 'newList': newList, 'pageData': pageData, })
修改路由
由于新闻动态中的三个子页面共享同一个路由,因此删除原先的路由,重新编辑
newsApp/urls.py:
from django.urls import path from . import views app_name = 'newsApp' urlpatterns = [ path('news/<str:newName>/',views.news,name='news')#新闻列表 ]
要从URL中捕获值,需要使用尖括号<>来定义路由附带的参数,参数类型次数为str,参数名称为newName
修改网页链接
打开base.html,修改“新闻动态”部分代码
<ul class="dropdown-menu"> <li><a href="{% url 'newsApp:news' 'company' %}">社团要闻</a></li> <li><a href="{% url 'newsApp:news' 'industry' %}">学院新闻</a></li> <li><a href="{% url 'newsApp:news' 'notice' %}">通知公告</a></li> </ul>
每个产品的链接href属性均采用下述形式:
href="{% url 'productsApp:products' 'robot' %}" href="{% url '应用名:路由名' '字符串' %}"
最后的字符串是参数。通过使用路由传参,只需要定义一个通用的URL映射入口,视图处理函数就能渲染不同的页面。