Wagtail supports multiple sites with different domains using site specific root pages and settings. Snippets exist globally and this is how to make them site specific.The goal is to have a filtered list of snippets based on the currently active site.
Add site field to the snippet model, in order to assign a snippet to a site.
class FAQ(ClusterableModel):
site = models.ForeignKey(
Site,
on_delete=models.CASCADE,
related_name="+",
null=True,
blank=True,
help_text="Is this snippet specific to the current site?",
)
# other fields
panels = [
FieldPanel("site"),
# other field panels
]
In order to filter the list of snippets, create a SnippetViewSet.
class SiteSnippetViewSet(SnippetViewSet):
"""Snippet viewset that is scoped for the current site.
Note that the snippet needs to have a site field."""
base_model: type[models.Model]
icon = "snippet"
def get_queryset(self, request):
qs: models.QuerySet[models.Model] | None = super().get_queryset(request)
if qs is None:
qs = self.base_model.objects.all()
current_site = Site.find_for_request(request)
return qs.filter(models.Q(site=current_site) | models.Q(site=None))
Register the FAQ snippet using a custom view set that inherits from the SiteSnippetViewSet.
class FAQ(ClusterableModel):
site = models.ForeignKey(
Site,
on_delete=models.CASCADE,
related_name="+",
null=True,
blank=True,
help_text="Is this snippet specific to the current site?",
)
# other fields
panels = [
FieldPanel("site"),
# other field panels
]
class FAQViewSet(SiteSnippetViewSet):
base_model = FAQ
register_snippet(FAQ, viewset=FAQViewSet)
Navigate to your snippets, assign them to the correct site and change the domain. You will only see the snippets that are assigned to the current site!