iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 7
0
自我挑戰組

Django CMS框架 - Wagtail筆記系列 第 7

[Day 7] 對Page自定義route

  • 分享至 

  • xImage
  •  

今天,我們將會使用RoutablePageMixin讓我們的page可以依照不同的route給予不同的內容,之後我們的wagtail就可以處理某些類型的URL,例如用category和tag進行頁面的分類。

Router

讓我們先來看看官方文件

A Page using RoutablePageMixin exists within the page tree like any other page, but URL paths underneath it are checked against a list of patterns. If none of the patterns match, control is passed to subpages as usual (or failing that, a 404 error is thrown).

所以我們就可以利用RoutablePageMixin在

http://127.0.0.1:8000/blog/category/category_test_1/
或者
http://127.0.0.1:8000/blog/tag/test_tag/

等url上作page的routing

首先,我們要先把app新增到我們的settings裡面

INSTALLED_APPS = [
   ...
   "wagtail.contrib.wagtailroutablepage",
   ...
]

更改models.py

首先更改Blog_Index_Page

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import datetime
from datetime import date

from django import forms
from django.db import models
from django.http import Http404, HttpResponse
from django.utils.dateformat import DateFormat
from django.utils.formats import date_format

import wagtail
from wagtail.admin.edit_handlers import (FieldPanel, FieldRowPanel,
                                         InlinePanel, MultiFieldPanel,
                                         PageChooserPanel, StreamFieldPanel)
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from wagtail.core import blocks
from wagtail.core.fields import RichTextField, StreamField
from wagtail.core.models import Page
from wagtail.embeds.blocks import EmbedBlock
from wagtail.images.blocks import ImageChooserBlock
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.snippets.models import register_snippet

from blog.blocks import TwoColumnBlock
from modelcluster.fields import ParentalKey, ParentalManyToManyField
from modelcluster.tags import ClusterTaggableManager
from taggit.models import Tag as TaggitTag
from taggit.models import TaggedItemBase
from wagtailmd.utils import MarkdownField, MarkdownPanel


class Blog_Index_Page(RoutablePageMixin, Page):
    description = models.CharField(max_length=255, blank=True,)

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

    def get_context(self, request, *args, **kwargs):
        context = super(BlogPage, self).get_context(request, *args, **kwargs)
        context['posts'] = self.posts
        context['blog_page'] = self
        return context

    def get_posts(self):
        return PostPage.objects.descendant_of(self).live()

    @route(r'^tag/(?P<tag>[-\w]+)/$')
    def post_by_tag(self, request, tag, *args, **kwargs):
        self.search_type = 'tag'
        self.search_term = tag
        self.posts = self.get_posts().filter(tags__slug=tag)
        return Page.serve(self, request, *args, **kwargs)

    @route(r'^category/(?P<category>[-\w]+)/$')
    def post_by_category(self, request, category, *args, **kwargs):
        self.search_type = 'category'
        self.search_term = category
        self.posts = self.get_posts().filter(categories__slug=category)
        return Page.serve(self, request, *args, **kwargs)

    @route(r'^$')
    def post_list(self, request, *args, **kwargs):
        self.posts = self.get_posts()
        return Page.serve(self, request, *args, **kwargs)
 

我們讓Blog_Index_Page繼承了RoutablePageMixin

並且定義了post_by_tag, post_by_category, post_list三個不同的function對應不同的route

現在BlogPage可以處理category和tag的URL,我們利用了

 self.posts = self.get_posts().filter(tags__slug=tag)

self.posts = self.get_posts().filter(categories__slug=category)

來過濾tag和category

接著更改Blog_page

class Blog_Page(Page):
    body = RichTextField(blank=True)
    date = models.DateTimeField(verbose_name="Post date", default=datetime.datetime.today)
    categories = ParentalManyToManyField('blog.BlogCategory', blank=True)
    tags = ClusterTaggableManager(through='blog.BlogPageTag', blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
        FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
        FieldPanel('tags'),
    ]

    settings_panels = Page.settings_panels + [
        FieldPanel('date'),
    ]

    @property
    def blog_page(self):
        return self.get_parent().specific

    def get_context(self, request, *args, **kwargs):
        context = super(PostPage, self).get_context(request, *args, **kwargs)
        context['blog_page'] = self.blog_page
        return context

我們在BlogPage中添加了一個新的字段日期,創建頁面時會建立。為了使使用者可以調整,我們還將其添加到Page.settings_panels

然後我們最後下migrations

python manage.py makemigrations blog
python manage.py migrate blog

修改blog_index_page.html

{% load wagtailcore_tags wagtailroutablepage_tags%}

{% block content %}
    <h1>{{ page.title }}</h1>

    {{ page.body|richtext }}

    <p><a href="{{ page.get_parent.url }}">Return to blog</a></p>

{% endblock %}


{% if page.tags.all.count %}
    <div class="tags">
        <h3>Tags</h3>
        {% for tag in page.tags.all %}
            <a href="{% routablepageurl blog_page "post_by_tag" tag.slug %}">{{ tag }}</a>
        {% endfor %}
    </div>
{% endif %}

{% with categories=page.categories.all %}
    {% if categories %}
        <h3>Categories</h3>
        <ul>
            {% for category in categories %}
                <li style="display: inline">
                    <a href="{% routablepageurl blog_page "post_by_category" category.slug %}">{{ category.name }}</a>
                </li>
            {% endfor %}
        </ul>
    {% endif %}
{% endwith %}

接著我們就可以用上面的url來對category和tag進行搜索了!!!


上一篇
[Day 6] 使用Tag來標記你的Page
系列文
Django CMS框架 - Wagtail筆記7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言