Skip to content

Instantly share code, notes, and snippets.

@KalobTaulien
Created July 21, 2018 23:36
Show Gist options
  • Save KalobTaulien/d70d0e725c5b9b9064b936c636c3acd9 to your computer and use it in GitHub Desktop.
Save KalobTaulien/d70d0e725c5b9b9064b936c636c3acd9 to your computer and use it in GitHub Desktop.
Wagtail 2: Creating a Blog with Blog Listing Page and Detail Pages
# -*- coding: utf-8 -*-
"""Blog app models."""
from django.db import models
from django.utils import timezone
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.core.fields import RichTextField, StreamField
from wagtail.core.models import Page
from wagtail.images.models import Image
from wagtail.search import index
from .streamfields import blocks
class BlogPage(Page):
"""Blog Detail Page (ie. Blog Post)."""
template = 'templates/blog/detail.html'
parent_page_type = ["pages.BlogListingPage"]
featured_image = models.ForeignKey(
Image,
related_name='+',
blank=True,
null=True,
on_delete=models.SET_NULL
)
summary = RichTextField(blank=True)
content = StreamField(
blocks.basic_streams,
null=True
)
publish_date = models.DateField(default=timezone.now)
search_fields = Page.search_fields + [
index.SearchField('summary'),
index.SearchField('content'),
]
def get_context(self, request, *args, **kwargs):
"""Provide additional context information."""
context = super().get_context(request)
# context['extra'] = 'Extra! Extra! Read all about it!'
return context
class Meta:
"""Meta information."""
verbose_name = "Blog Detail Page"
verbose_name_plural = "Blog Detail Pages"
class BlogListingPage(Page):
"""Blog Listing page class."""
template = "templates/blog/list.html"
parent_page_type = ["wagtailcore.Page"]
subpage_types = [
BlogPage,
]
# More fields here
# Adding fields to admin as "panels"
content_panels = [
FieldPanel("title", classname="full title"),
# More panels for more fields
]
class Meta:
"""Meta information."""
verbose_name = "Blog Listing Page"
verbose_name_plural = "Blog Listing Pages"
@classmethod
def can_create_at(cls, parent):
"""You can only create one of these, unless you have 2 blogs on your site."""
return super().can_create_at(parent) and not cls.objects.exists()
def get_context(self, request, *args, **kwargs):
"""
Adding the blog posts to the context.
This will get all BlogPage's from all over your wagtail website, not just children.
"""
context = super().get_context(request)
context["blog_posts"] = BlogPage.objects.live().order_by("-id")
return context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment