feed是一个内建聚合提要框架,可据此动态生成RSS或Atom
RSS(简易信息聚合)是一种消息来源格式规范,用以聚合经常发布更新数据的网站,例如博客文章、新闻、音频或视频的网摘。RSS文件(或称做摘要、网络摘要、或频更新,提供到频道)包含全文或是节录的文字,再加上发布者所订阅之网摘数据和授权的元数据。
在blog下新建feeds.py文件
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.contrib.syndication.views import Feed
from django.template.defaultfilters import truncatewords
from .models import Post
class LatestPostsFeed(Feed):
title = 'My blog'
link = '/blog/'
description = 'New posts of my blog.'
def items(self):
return Post.published.all()[:5] #检索最后5个发布的帖子
def item_title(self, item):
return item.title
def item_description(self, item):
return truncatewords(item.body,30) #使用内建模板过滤器构建博客帖子的描述内容
编辑blog/urls.py
导入刚刚创建的LatestPostsFeed,并在新的url中实例化提要内容
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.urls import path
from . import views
from .feeds import LatestPostsFeed
app_name = 'blog'
rlpatterns = [
path('', views.post_list, name='post_list'),
# path('', views.PostListView.as_view(), name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
path('<int:post_id>/share/', views.post_share, name='post_share'),
path('tag/<slug:tag_slug>',views.post_list,name='post_list_by_tag'),
# path('sitemap.xml',sitemap,{'sitemaps':sitemaps},name='django.contrib.sitemaps.views.sitemap')
path('feed/', LatestPostsFeed(), name='post_feed'),
]
结果:http://127.0.0.1:8000/blog/feed/
在google浏览器打开
在blog/base.py中(侧栏div下,全部帖子下方)添加如下代码
<p>
<a href="{% url "blog:post_feed" %}">Subscribe to my RSS feed</a>
</p>
打开http://127.0.0.1:8000/blog/