Skip to content

Instantly share code, notes, and snippets.

@KalobTaulien
Created April 23, 2019 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KalobTaulien/70f6021487753ca2ef86b3e1f9755aea to your computer and use it in GitHub Desktop.
Save KalobTaulien/70f6021487753ca2ef86b3e1f9755aea to your computer and use it in GitHub Desktop.
Wagtail: Adding author filtering
# blog/models.py
# Nothing in this class has changed. I just put it here for reference.
class BlogAuthor(models.Model):
"""Blog author for snippets."""
name = models.CharField(max_length=100)
website = models.URLField(blank=True, null=True)
image = models.ForeignKey(
"wagtailimages.Image",
on_delete=models.SET_NULL,
null=True,
blank=False,
related_name="+",
)
# Added filterable context based on the ?author=x query string parameter
class BlogListingPage(RoutablePageMixin, Page):
"""Listing page lists all the Blog Detail Pages."""
# Fields here
def get_context(self, request, *args, **kwargs):
"""Adding custom stuff to our context."""
context = super().get_context(request, *args, **kwargs)
# Get all posts
all_posts = BlogDetailPage.objects.live().public().order_by('-first_published_at')
# This is the filterable part.
# Start author filter.
if request.GET.get('author', None):
author_id = request.GET.get('author')
all_posts = all_posts.filter(blog_authors__author__id=author_id)
# End author filter.
# Paginate all posts by 2 per page
paginator = Paginator(all_posts, 2)
# Try to get the ?page=x value
page = request.GET.get("page")
try:
# If the page exists and the ?page=x is an int
posts = paginator.page(page)
except PageNotAnInteger:
# If the ?page=x is not an int; show the first page
posts = paginator.page(1)
except EmptyPage:
# If the ?page=x is out of range (too high most likely)
# Then return the last page
posts = paginator.page(paginator.num_pages)
# "posts" will have child pages; you'll need to use .specific in the template
# in order to access child properties, such as youtube_video_id and subtitle
context["posts"] = posts
return context
{% extends "base.html" %}
{# templates/blog/blog_listing_page.html #}
{% block content %}
{% for post in posts %}
<h2>{{ post.custom_title }}</h2>
<div>
Posted by:
{% for orderable in post.blog_authors.all %}
<a href="/blog/?author={{ orderable.author.id }}">{{ orderable.author.name }}</a>
{% endfor %}
</div>
{% endfor %}
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment