New Wagtail Course! 🥳 The Ultimate Wagtail Developers Course

Tutorial Wagtail Version: 2.x

Using Wagtails save() method to remove template caching

In the previous lesson we discovered how to save sections of a template and reduce the number of queries on any given page. But to delete the cache so that Wagtail CMS could update the page was a very manual task. In this tutorial, we'll learn how to use Wagtails save() method to delete specific template fragment cache from our site.

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/ (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 [] # Matches the 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"] ='-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.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:

And if you want to view the entire repo with all the course progress so far, all the video tutorial code is available at

Related tutorials

The Ultimate Wagtail Developers Course

This course covers everything from basic installation to advanced features like custom blocks and API integration, it's perfect for developers looking to enhance their skills with this powerful CMS.

Ultimate Wagtail Developers Course Logo