Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Django学习记录(二十一):Django by example -- Blog(十七) #57

Open
PyxYuYu opened this issue Dec 1, 2016 · 0 comments
Open
Labels

Comments

@PyxYuYu
Copy link
Owner

PyxYuYu commented Dec 1, 2016

Life is a maze and love is a riddle.

0x01 Django

  • Build a Blog Application
    • Creating feeds for your blog posts
      • blog 文件夹下创建 feeds.py
        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]
      	  
      	  def item_title(self, item):
      	      return item.title
      		 
      	  def item_description(self, item):
      	      return truncatewords(item.body, 30)
      • title link description 3个属性分别对应 RSS 中的 <title> <link> <description> 元素
      • items() 函数为 feed 选取5个公开 posts
      • item_title() 函数 和 item_description() 函数返回了选取的 posts 对应的 title description (这里用 truncatewords() 截取了30个单词)
      • 完成 feeds.py 后,在 blog/urls.py 中导入刚刚创建的 LatestPostsFeed ,匹配一个新的 URL
        from .feeds import LatestPostsFeed
        
        urlpatterns = [
            #...
      	  url(r'^feed/$', LatestPostsFeed(), name='post_feed'),
        ]
      • 打开 http://localhost:8000/blog/feed/ 就可以看到 RSS feed (包括了5个 posts
      • 在模板中添加一个订阅链接,只需要编辑 blog/base.html ,在 total posts 下添加
        <p><a href="{% url "blog:post_feed" %}">Subscribe to my RSS feed</a></p>
@PyxYuYu PyxYuYu added the Django label Dec 1, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant