New Wagtail Course! 🥳 The Ultimate Wagtail Developers Course

Tutorial Wagtail Version: 2.x

Registering Snippets using Django Models

Snippets are Wagtails way of re-using existing data. For example, being able to select a Blog Author (or multiple authors) instead of having to add a name, image and website for every blog author in every blog post you make; instead you can simply fill out a form once, and re-use the final data with a couple of clicks.

"Snippets are pieces of content which do not necessitate a full webpage to render."

Above is the line from the Wagtail Docs that describes a Snippet. It's accurate, but maybe a bit tricky to understand at first.

You can think of a Snippet like pieces of data that you can re-use. If you're familiar with the coding notion of functions (re-usable chunks of code), then you can think of a Snippet as a function for storing and retrieving data from the Wagtail Admin.

Some example where Snippets are useful:

  • Menus
  • Blog Authors
  • Blog Categories
  • Advertisements

In this video we'll be using Blog Authors as the the example. Here's a copy & paste example you can use:

``` """Blog Author Snippet.""" from django.db import models from wagtail.admin.edit_handlers import ( FieldPanel, MultiFieldPanel, ) from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.models import register_snippet #@register_snippet # uncomment to use a decorator instead of a function class BlogAuthor(models.Model): """Blog author for snippets.""" name = models.CharField(max_length=100) website = models.URLField(blank=True, null=True) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.SET_NULL, null=True, blank=False, related_name="+", ) panels = [ MultiFieldPanel( [ FieldPanel("name"), ImageChooserPanel("image"), ], heading="Name and Image", ), MultiFieldPanel( [ FieldPanel("website"), ], heading="Links" ) ] def __str__(self): """String repr of this class.""" return self.name class Meta: # noqa verbose_name = "Blog Author" verbose_name_plural = "Blog Authors" register_snippet(BlogAuthor) ```
The Git Commit

Videos not your thing? That's OK. Here's the link the full Git Commit so you can see what was added in this video at a glance.

https://github.com/CodingForEverybody/learn-wagtail/commit/de5e86e29802c1548cabb148ca0e41dafcfe928d

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