Learn Wagtail Course

Using Wagtails save() method to remove template caching

This is second tutorial about template fragment caching. If you're new to template caching, please check out the first tutorial to get an idea of what template caching is and how to apply it.

In the previous tutorial we added template caching to our website, and I demonstrated how it's good and bad. And deleting template cache was a manual job, which is no way to live your life.

In this tutorial we'll learn how to automatically remove template fragment caching when you save a Wagtail Page.

blog/models.py (The Model)

from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key

from wagtail.core.models import Page 


class BlogDetailPage(Page):

    # Your Page fields and panels here...

    def save(self, *args, **kwargs):
        """Create a template fragment key.
        Then delete the key."""
        key = make_template_fragment_key(
            "blog_post_preview",  # Matches the name of our template fragment in the blog_listing_page.html
            [self.id]  # Matches the post.id in the template for loop (shown below)
        )
        cache.delete(key)
        return super().save(*args, **kwargs)


class BlogListingPage(Page):

    # Fields and panels 

    def get_context(self, request, *args, **kwargs):
        """Adding blog posts to our context."""
        context = super().get_context(request, *args, **kwargs)
        # This is used in our template loop
        context["posts"] = BlogDetailPage.objects.live().public().order_by('-first_published_at')
        return context

blog/blog_listing_page.html (The Template)

{% extends "base.html" %}
{% load cache %}

{% block content %}

    {% for post in posts %}
        {% cache 604800 blog_post_preview post.id %}
           {{ post.title }}
           {{ post.url }}
        {% endcache %}
    {% endfor %}

{% endblock content %}

The Git Commit

If you'd like to see the entire Git Commit, with all 12 lines that were added, here's the link: https://github.com/CodingForEverybody/learn-wagtail/commit/f9423929d815f8c3c960b849a57b606728aace0c

And if you want to view the entire repo with all the course progress so far, all the learnwagtail.com video tutorial code is available at https://github.com/CodingForEverybody/learn-wagtail

Was this helpful to you?

Sharing is caring. Help the community by sharing this article.