Wagtail 教程 2:简单博客实现

Wagtail 教程系列 记录了基于 Wagtail 搭建博客站点的整个过程,博客站点 所呈现的即是搭建过程的最新效果。

更多 Wagtail 内容:https://slowread.cn/wagtail-tutorials

博客列表和文章正文

  • 执行 python manage.py startapp blog 创建 blog app.
  • 编辑 slowread/settings/base.py 在 INSTALLED_APPS 中添加 blog app.

博客列表实现

编辑 blog/models.py 添加以下内容:

from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel

class BlogIndexPage(Page):
    intro = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('intro', classname="full")
    ]

Copy

执行 python manage.py makemigrations && python manage.py migrate

因为模型名字为BlogIndexPage,因此模板文件的名字就成了blog/templates/blog/blog_index_page.html,模板文件内容如下:

{% extends "base.html" %}

{% load wagtailcore_tags %}

{% block body_class %}template-blogindexpage{% endblock %}

{% block content %}
    

{{ page.title }}

{{ page.intro|richtext }}
{% for post in page.get_children %}

{{ post.title }}

{{ post.specific.intro }} {{ post.specific.body|richtext }} {% endfor %} {% endblock %}

Copy

博客正文实现

编辑 blog/models.py 添加以下内容:

from django.db import models

from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.search import index

# Keep the definition of BlogIndexPage, and add:

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full"),
    ]

Copy

执行 python manage.py makemigrations && python manage.py migrate.

新建模板文件 blog/templates/blog/blog_page.html ,内容如下:

{% extends "base.html" %}

{% load wagtailcore_tags %}

{% block body_class %}template-blogpage{% endblock %}

{% block content %}
    

{{ page.title }}

{{ page.date }}

{{ page.intro }}
{{ page.body|richtext }}

Return to blog

{% endblock %}

Copy

查看效果

进入 Wagtail 管理后台:

  1. 选择 页面,Home,添加子页面,Blog index page,编辑博客列表标题,发布;
  2. 选择 页面,Home,点击上一步创建的 Blog index page 最右侧右箭头,添加子页面,选择 Blog page,编辑博客文章内容,发布;重复几次发布几篇不同文章;

打开 http://127.0.0.1:8000/blog ,查看效果。

一点改进

  1. 博客文章列表根据创建时间倒叙排列。
  2. 只显示发布的文章。

编辑 blog/models.py ,修改以下相应内容:

class BlogIndexPage(Page):
    intro = RichTextField(blank=True)

    def get_context(self, request):
        # Update context to include only published posts, ordered by reverse-chron
        context = super().get_context(request)
        blogpages = self.get_children().live().order_by('-first_published_at')
        context['blogpages'] = blogpages
        return context

Copy

编辑 blog/templates/blog/blog_index_page.html,修改 {% for post in page.get_children %} 为 {% for post in blogpages %}。

现在,可以在管理后台撤销发布一篇文章,查看效果。

图像

编辑 blog/models.py 添加 BlogPageGalleryImage model,内容如下:

from django.db import models

# New imports added for ParentalKey, Orderable, InlinePanel, ImageChooserPanel

from modelcluster.fields import ParentalKey

from wagtail.core.models import Page, Orderable
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.search import index

# ... (Keep the definition of BlogIndexPage, and update BlogPage:)

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full"),
        InlinePanel('gallery_images', label="Gallery images"),
    ]

class BlogPageGalleryImage(Orderable):
    page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images')
    image = models.ForeignKey(
        'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
    )
    caption = models.CharField(blank=True, max_length=250)

    panels = [
        ImageChooserPanel('image'),
        FieldPanel('caption'),
    ]

Copy

执行 python manage.py makemigrations && python manage.py migrate.

编辑博客文章页面模板文件 blog/templates/blog/blog_page.html ,内容如下:

{% extends "base.html" %}

{% load wagtailcore_tags wagtailimages_tags %}

{% block body_class %}template-blogpage{% endblock %}

{% block content %}
    

{{ page.title }}

{{ page.date }}

{{ page.intro }}
{{ page.body|richtext }} {% for item in page.gallery_images.all %}
{% image item.image fill-320x240 %}

{{ item.caption }}

{% endfor %}

Return to blog

{% endblock %}

Copy

现在,可以在管理后台,编辑一篇文章,增加图片内容,然后发布,查看效果。

再次改进博客列表显示效果,编辑 blog/models.py 修改 BlogPage model 为下面内容:

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)

    def main_image(self):
        gallery_item = self.gallery_images.first()
        if gallery_item:
            return gallery_item.image
        else:
            return None

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full"),
        InlinePanel('gallery_images', label="Gallery images"),
    ]

Copy

编辑博客文章页面模板文件 blog/templates/blog/blog_index_page.html ,内容如下:

{% extends "base.html" %}

{% load wagtailcore_tags wagtailimages_tags %}

{% block body_class %}template-blogindexpage{% endblock %}

{% block content %}
    

{{ page.title }}

{{ page.intro|richtext }}
{% for post in blogpages %} {% with post=post.specific %}

{{ post.title }}

{% with post.main_image as main_image %} {% if main_image %}{% image main_image fill-160x100 %}{% endif %} {% endwith %}

{{ post.intro }}

{{ post.body|richtext }} {% endwith %} {% endfor %} {% endblock %}

Copy

查看效果,包含图像的文章在博客列表页面增加了缩略图显示。

标签

再次修改 blog/models.py , 增加/修改以下相应内容:

from django.db import models

# New imports added for ClusterTaggableManager, TaggedItemBase, MultiFieldPanel

from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase

from wagtail.core.models import Page, Orderable
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.search import index

# ... (Keep the definition of BlogIndexPage)

class BlogPageTag(TaggedItemBase):
    content_object = ParentalKey(
        'BlogPage',
        related_name='tagged_items',
        on_delete=models.CASCADE
    )

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)
    tags = ClusterTaggableManager(through=BlogPageTag, blank=True)

    # ... (Keep the main_image method and search_fields definition)

    content_panels = Page.content_panels + [
        MultiFieldPanel([
            FieldPanel('date'),
            FieldPanel('tags'),
        ], heading="Blog information"),
        FieldPanel('intro'),
        FieldPanel('body'),
        InlinePanel('gallery_images', label="Gallery images"),
    ]

Copy

执行 python manage.py makemigrations && python manage.py migrate.

进入管理后台,编辑部分博客文章,增加自定义标签。

编辑博客文章页面模板文件 blog/templates/blog/blog_page.html ,在文件最后增加如下内容:

{% if page.tags.all.count %}
    

标签

{% for tag in page.tags.all %} {% endfor %}
{% endif %}

Copy

修改 blog/models.py , 增加 BlogTagIndexPage model,内容如下:

class BlogTagIndexPage(Page):

    def get_context(self, request):

        # Filter by tag
        tag = request.GET.get('tag')
        blogpages = BlogPage.objects.filter(tags__name=tag)

        # Update template context
        context = super().get_context(request)
        context['blogpages'] = blogpages
        return context

Copy

执行 python manage.py makemigrations && python manage.py migrate.

进入管理后台,在 Home 页面下,增加 Blog tag index page 类型的子页面,名字为 标签,推荐中缩略名为 tags。

新建对应标签页的页面模板文件 blog/blog_tag_index_page.html,内容如下:

{% extends "base.html" %}
{% load wagtailcore_tags %}

{% block content %}

    {% if request.GET.tag|length %}
        

Showing pages tagged "{{ request.GET.tag }}"

{% endif %} {% for blogpage in blogpages %}

{{ blogpage.title }}
Revised: {{ blogpage.latest_revision_created_at }}
{% if blogpage.author %}

By {{ blogpage.author.profile }}

{% endif %}

{% empty %} No pages found with that tag. {% endfor %} {% endblock %}

Copy

打开 http://127.0.0.1:8000/blog/ ,查看效果。

更多 Wagtail 内容:https://slowread.net/tags/?tag=Wagtail

你可能感兴趣的:(Wagtail 教程 2:简单博客实现)