Registering Snippets using Django Models
"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
Was this helpful to you?
Sharing is caring. Help the community by sharing this article.
Kalob Taulien
Fullstack web developer and online web dev. instructor.