def test_published_posts_exclude_unpublished_posts(self): # Count the number of posts in db postsCount = len(Post.objects.all()) self.assertEqual(len(Post.published_posts()), postsCount - 1) # unpublish a post, should result in 1 published and 2 unpublished p2 = Post.objects.get(title="test post 2") p2.unpublish() self.assertEqual(len(Post.published_posts()), postsCount - 2) # publish a post, should go back to 2 published and 1 unpublished p3 = Post.objects.get(title="test post 3") p3.publish() self.assertEqual(len(Post.published_posts()), postsCount - 1)
def index(request): """ Index function, this is called by the / pattern from news.urls This means that this function is called on the url http://APP_URL/posts. TODO: Use a template to presents the posts """ posts = Post.published_posts().order_by('-pub_date') # Render paginated page return paginated_news_index(request, posts)
def latest(request): """ Retrieves the latest published post and prints it First we filter out the unpublished posts and then we get the last element. If there is no latest post (for instance if there are no published news) we print out 'No posts yet!' TODO: Use a template to display the latest post """ try: latest_post = Post.published_posts().latest('pub_date') return HttpResponse("%s <br> %s" % (latest_post.title, latest_post.content)) except Post.DoesNotExist: return HttpResponse("No posts yet!")
def item(request, post_id): """ Displays a single post with id post_id. Is called by the pattern /$post_id from news.url First we need to filter out the unpublished posts in case the requested post is not yet published and then we try to get that post. If it does not exist we just print 'No such post' as of now. TODO: Use a template to present the post """ try: post = Post.published_posts().get(id=post_id) content = "Posts article: %s<br> %s" return HttpResponse(content % (post_id,post.content)) except Post.DoesNotExist: return HttpResponse("No such post")
def rss(request): """ Retrieves all posts and renders them in a rss xml fashion. """ posts = Post.published_posts().order_by('-pub_date') return render(request, 'news/feed.dtl', { 'items' : posts })