将日期添加到博客页面的URL

时间:2015-11-19 19:51:02

标签: django wagtail

我正在建造我的第一个wagtail django网站。我的网站有一个博客部分,我想在网址中添加发布日期。目前,在添加页面时,URL变为:example.com/blog/[slug]但我希望它是:example.com/blog/2015/11/19/[slug]

我的博客页面:

class BlogPage(Page):
    main_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )
    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'),
        ImageChooserPanel('main_image'),
        FieldPanel('intro'),
        FieldPanel('body'),
    ]

2 个答案:

答案 0 :(得分:0)

我不确定你是否可以将它与wigtail整合在一起,但这里有一个如何用django实现的例子:

  1. 更新您的模型以自动生成blog/models.py中的slug( E.g :基于标题):
  2. from django.db import models
    from django.utils.text import slugify
    from django.utils.timezone import now
    
    class Post(models.Model):
        # your attributes
        date = models.DateTimeField(default=now())
        title = models.CharField(max_length=250)
        slug = models.SlugField()
    
        def save(self):
            """
            Generate and save slug based on title
            """
            super(Post, self).save()
            self.slug = slugify(self.title)
            super(Post, self).save()
    
    1. 在您的博客应用中添加新网址(blog/urls.py):
    2. url(r'^(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/(?P<slug>[\w-]+)$', views.post_details)
      
      1. 定义视图以获取blog/views.py中的帖子:
      2. def post_details(request, year, month, day, slug):
            post = Post.objects.get(slug=slug, date__year=year, date__month=month, date__day=day)
            # do what you want with this post
        

答案 1 :(得分:0)

这是实现此解决方案的更具Wagtail特定方式,它假设您还有一个BlogIndexPage,其中包含下面的所有博客页面。虽然即使您的BlogPages存在于HomePage下也可以使用,但只需相应地移动您的路由方法。

概述:

  • 我们将更新BlogPageIndex(或您的博客页面所在的任何页面)上的子URL。我们通过添加mixin RoutablePageMixin来完成此操作。
  • 然后,我们可以将@route用作BlogPageIndex上方法的装饰器,用于我们想要的任何类型的自定义视图。
  • 最后,我们需要更新我们的BlogPage模型,以便其正常的URL将遵循我们的新URL映射。我们通过覆盖BlogPage上的set_url_path来完成此操作。
  • 这将使用BlogPage模型中的常规slug字段和字段date_published生成新的url_path

参见示例/myapp/models.py

from django.shortcuts import get_object_or_404

from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from wagtail.wagtailcore.models import Page


class BlogPage(Page):
    # using date_published instead of date to reduce ambiguity
    date_published = models.DateField(
        "Date post published", blank=True, null=True
    )
    # ...other fields:  main_image, intro, body
    # ...search_fields
    # ...content_panels

    # override the set_url_path method to use generate different URL
    # this is updated on save so each page will need to be re-published
    # old URL will still work
    def set_url_path(self, parent):
        # initially set the attribute self.url_path using the normal operation
        super().set_url_path(parent=parent)
        self.url_path = self.url_path.replace(
            self.slug, '{:%Y/%m/%d/}'.format(self.date_published) + self.slug
        )


class BlogIndexPage(RoutablePageMixin, Page):
    # note - must inherit RoutablePageMixin AND Page

    # ...other fields
    # ...search_fields
    # ...content_panels

    # route for sub-pages with a date specific URL for posts
    # this will NOT make a list of pages at blog/2018 just specific blogs only
    @route(r'^(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/(?P<slug>[\w-]+)/?$')
    def blog_page_by_date(self, request, year, month, day, slug, name='blog-by-date'):
        """Serve a single blog page at URL (eg. .../2018/01/23/my-title/)"""
        blog_page = get_object_or_404(
            BlogPage,
            date_published__year=year,
            date_published__month=month,
            date_published__day=day,
            slug=slug
        )
        return blog_page.serve(request)

    # Speficies that only BlogPage objects can live under this index page
    subpage_types = ['BlogPage']

注意事项:

  • 需要重新保存每个现有博客页面以触发对url_path的更新。
  • 原始url_path仍然有效,重定向,可以通过覆盖serve方法并检查是否已使用旧网址,然后重定向来添加重定向。 / LI>
  • 这并不考虑使用多个页面URL的任何SEO含义。