pythondjangodjango-templateswagtaildjango-modeltranslation

Wagtail-ModelTranslation Template Fragment Caching


I've implemented a multilingual site using wagtail and wagtail-modeltranslation but I'm having a problem with template fragment caching. The cache works but is not respecting the separate languages. Whichever language is accessed first after a save, is the one that will be served for all languages. I've tried two ways of setting the cache key to no avail. First from the django docs, second trying to explicitly include the language code in the template

First:

{% cache 604800 about_copy LANGUAGE_CODE %}
... HTML ...
{% endcache %}

Second: Using a simple template tag

from django.utils.translation import get_language

@register.simple_tag(takes_context=True)
def get_lang(context, *args, **kwargs):
    return get_language()
{% cache 604800 about_copy get_lang %}
... HTML ...
{% endcache %}

My save method is as follows:

    def save(self, *args, **kwargs):
        """Create a template fragment key.
        Then delete the key."""

        key = make_template_fragment_key("about_copy")
        cache.delete(key)

        return super().save(*args, **kwargs)

This does clear the correct fragment regardless of not including any language related arguments

Any help would be greatly appreciated. Thanks!


Solution

  • Your first approach should work provided LANGUAGE_CODE is actually defined in the context. This doesn't happen automatically, so you probably just need to set it first:

    {% load i18n %}
    {% get_current_language as LANGUAGE_CODE %}
    
    {% cache 604800 about_copy LANGUAGE_CODE %}
    ... HTML ...
    {% endcache %}
    

    A side note here is that you need to be careful with template fragment caching in Wagtail, because previewed, non-published content will get cached.