In this tutorial we'll be learning how to register another Wagtail Snippet, but instead of using an Orderable and a SnippetChooserPanel (like the previous lesson) we're going to use a ParentalManyToManyField and a form widget to create Checkboxes in the Wagtail Admin.
Sometimes you want to be able to see every option available from a snippet. A good example is when you select Blog Categories. If you had to select one at a time through a SnippetChooserPanel then you're making the end user click too much, and you're also making it harder for them to see every Blog Category in one glance.
In this tutorial we'll create checkboxes. The end result looks like this:
Below is a quick cut of the code from this lesson for those who like to copy and paste. For a full view of all the changes you'll want to look at the full Git Commit.
"""blog/models.py""" from django import forms from django.db import models from modelcluster.fields import ParentalManyToManyField from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel from wagtail.core.models import Page from wagtail.snippets.models import register_snippet @register_snippet class BlogCategory(models.Model): """Blog category for a snippet.""" name = models.CharField(max_length=255) slug = models.SlugField( verbose_name="slug", allow_unicode=True, max_length=255, help_text='A slug to identify posts by this category', ) panels = [ FieldPanel("name"), FieldPanel("slug"), ] class Meta: verbose_name = "Blog Category" verbose_name_plural = "Blog Categories" ordering = ["name"] def __str__(self): return self.name class BlogListingPage(Page): """Listing page lists all the Blog Detail Pages.""" # ... def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context.""" context = super().get_context(request, *args, **kwargs) context["posts"] = BlogDetailPage.objects.live().public() # Example of getting all categories context["categories"] = BlogCategory.objects.all() return context class BlogDetailPage(Page): """Blog detail page.""" # Fields ... categories = ParentalManyToManyField("blog.BlogCategory", blank=True) content_panels = Page.content_panels + [ # ... MultiFieldPanel( [ FieldPanel("categories", widget=forms.CheckboxSelectMultiple) ], heading="Categories" ), # ... ]