I am trying to build a snippet based the Wagtail tutorial here.
I have built my snippet in models.py
and create a custom template tag in the templatetags
folder and connected the snippet to a Page
via ForeignKey
. I have also created the html template and run both makemigrations
and migrate
.
The Snippet is a header image and a caption which appears on all pages except for the homepage. Code as follows:
Snippet Model:
@register_snippet
class HeroImage(models.Model):
text = models.CharField(max_length=255)
image = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
panels = [
FieldPanel('text'),
ImageChooserPanel('image'),
]
def __str__(self):
return self.text
Snippet Custom Template Tag:
@register.inclusion_tag('hero_image.html', takes_context=True)
def hero_images(context):
self = context.get('self')
if self is None or self.depth <= 2:
hero = ()
else:
hero = HeroImage.objects.all()
return {
'hero': hero,
'request': context['request'],
}
Snippet connected to Page:
class MenuPage(Page):
hero = models.ForeignKey(
'home.HeroImage',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
content_panels = Page.content_panels + [
SnippetChooserPanel('hero'),
]
I have created two Snippets and selected one in my Page in the admin interface. In the template I have tried many different calls to the Snippet but they all return nothing. Calls I have tried include:
{{ page.hero }}
{{ page.hero.text }}
{{ hero.text }}
{{ page.hero_images }}
{{ page.hero_images.text }}
Etc...
Nothing has worked unfortunately, the only thing I managed to get working is by typing {{ hero }}
which returned <QuerySet [<HeroImage: Lorem Ipsum One>, <HeroImage: Lorem Ipsum Two>]>
What am I doing wrong?
In Visual studio code, close VSC and then open it again