如何格式化django生成的sitemap lastmod日期?

时间:2016-10-19 00:03:33

标签: python django sitemap

我的站点地图以这种方式生成:

from django.contrib.sitemaps import Sitemap
from django.utils import timezone

class StaticViewSitemap(Sitemap):
    priority = 0.5
    changefreq = 'daily'

        def items(self):
            return ['index', 'contacts']

        def lastmod(self, item):
            return timezone.now()

作为django docs says,lastmod返回datetime。它将sitemap.xml lastmod呈现为' yyyy-mm-dd'格式和外观如此:

<urlset>
    <url>
        <loc>http://127.0.0.1/index</loc>
       <lastmod>2016-10-19</lastmod>
       <changefreq>daily</changefreq>
    </url>
    <url>
       <loc>http://127.0.0.1/contacts</loc>
       <lastmod>2016-10-19</lastmod>
       <changefreq>daily</changefreq>
    </url>
</urlset>

但我怎么能将lastmod格式改为ISO8601(我需要这个:2008-01-02T10:30:00 + 02:00)才能得到这个:

<urlset>
    <url>
        <loc>http://127.0.0.1/index</loc>
       <lastmod>2016-10-19T00:25:00+03:00</lastmod>
       <changefreq>daily</changefreq>
    </url>
    <url>
       <loc>http://127.0.0.1/contacts</loc>
       <lastmod>2016-10-19T00:25:00+03:00</lastmod>
       <changefreq>daily</changefreq>
    </url>
</urlset>

我一直在制作自定义格式&#39;路径如here(Django格式本地化)但未找到我应该更改哪个设置以获得适当的日期格式。 感谢。

我的urls.py:

...

sitemaps = {
    'static': StaticViewSitemap
}

urlpatterns = [
    ...
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
    ...
]

1 个答案:

答案 0 :(得分:1)

在内置站点地图模板中,您有<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>

您需要覆盖模板并将当前格式修复为ISO格式,更多信息请点击此处:link

from django.contrib.sitemaps import views

urlpatterns = [
    path('custom-sitemap.xml', views.index, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }),
    path('custom-sitemap-<section>.xml', views.sitemap, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }, name='django.contrib.sitemaps.views.sitemap'),
]

此处所有格式代码的快速链接: https://docs.djangoproject.com/en/2.0/ref/contrib/sitemaps/#template-customization