From c4289980499e6a1d16fbbcc0253fd38d19207c2e Mon Sep 17 00:00:00 2001 From: David Ray Date: Fri, 10 Feb 2017 07:10:49 -0500 Subject: [PATCH] Add messages to base.html, handle /tags/ and /tags/[bad-slug]/ --- bakerydemo/blog/models.py | 20 ++++++++++++++------ bakerydemo/templates/base.html | 10 ++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/bakerydemo/blog/models.py b/bakerydemo/blog/models.py index ad4ba47..2e08d01 100644 --- a/bakerydemo/blog/models.py +++ b/bakerydemo/blog/models.py @@ -1,7 +1,8 @@ from __future__ import unicode_literals +from django.contrib import messages from django.db import models -from django.shortcuts import get_list_or_404, get_object_or_404, render +from django.shortcuts import redirect, render from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager @@ -150,16 +151,23 @@ class BlogIndexPage(RoutablePageMixin, Page): '-first_published_at') return context + @route('^tags/$', name='tag_archive') @route('^tags/(\w+)/$', name='tag_archive') def tag_archive(self, request, tag=None): ''' A Custom view that utilizes Tags. This view will - return all related BlogPages for a given Tag. + return all related BlogPages for a given Tag or redirect back to + the BlogIndexPage ''' - tag = get_object_or_404(Tag, slug=tag) - blogs = get_list_or_404( - BlogPage.objects.filter(tags=tag).live().descendant_of(self) - ) + try: + tag = Tag.objects.get(slug=tag) + except Tag.DoesNotExist: + if tag: + msg = 'There are no blog posts tagged with "{}"'.format(tag) + messages.add_message(request, messages.INFO, msg) + return redirect(self.url) + + blogs = BlogPage.objects.filter(tags=tag).live().descendant_of(self) context = { 'title': 'Posts tagged with: {}'.format(tag.name), diff --git a/bakerydemo/templates/base.html b/bakerydemo/templates/base.html index 1456e53..ead2ce8 100755 --- a/bakerydemo/templates/base.html +++ b/bakerydemo/templates/base.html @@ -112,6 +112,16 @@ {# breadcrumbs is defined in base/templatetags/navigation_tags.py #} {% endblock %} + {% if messages %} +
+ +
+ {% endif %} + {% block content %} {% endblock %}