7

我有以下模型关系:

class Section(models.Model):
    section = models.CharField(max_length=200, unique=True)
    name = models.CharField(max_length=200, blank = True)


class Article (models.Model):
    url = models.CharField(max_length = 30, unique=True)
    is_published = models.BooleanField()  
    section = models.ForeignKey(Section)

我需要为文章创建一个站点地图,其中包含部分的站点地图文件。我在这里阅读 django 文档http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/

但没有设法找到答案我怎么能:

  1. 在这种情况下定义站点地图类
  2. 如何将部分参数传递到 url 文件中(如文档中所述)
  3. 如果我在应用程序的另一个文件中将站点地图定义为 python 类,我从哪里可以获得 {'sitemaps': sitemaps}
4

3 回答 3

6

如果我理解正确,您想使用站点地图索引,该索引将指向每个部分的单独站点地图 xml 文件。

Django 通过为索引站点地图提供单独的站点地图视图来支持此功能。

以前没有使用过该功能,但以下内容可能适用于您的情况。

### sitemaps.py
from django.contrib.sitemaps import GenericSitemap
from models import Section

all_sitemaps = {}
for section in Section.objects.all():

    info_dict = {
        'queryset': section.article_set.filter(is_published=True),
    }

    sitemap = GenericSitemap(info_dict,priority=0.6)

    # dict key is provided as 'section' in sitemap index view
    all_sitemaps[section.name] = sitemap

### urls.py
from sitemaps import all_sitemaps as sitemaps

...
...
...

urlpatterns += patterns('',
        (r'^sitemap.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
        (r'^sitemap-(?P<section>.+)\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)
于 2009-09-08T18:28:40.080 回答
2
Django==2.2
Python==3.6

这是在 Django 中使用站点地图索引的更好更简单的方法,django.contrib.sitemaps通过将其添加INSTALLED_APPSsettings.py. 在您的应用程序中编写 sitemaps.py 文件并根据需要定义类。django.contrib.sitemap.Sitemap在站点地图类中扩展StaticViewSitemap静态 URL 的示例,确保您的所有静态 URL 都具有用于reverse查找的名称(从 URL 名称获取 URL)

# app/sitemap.py

from django.contrib import sitemaps
from django.urls import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.6
    changefreq = 'monthly'

    def items(self):
        # URLs names
        return ['index', 'aboutus', 'ourstory',]

    def location(self, item):
        return reverse(item)

在 urls.py 中导入所有站点地图导入站点地图和索引,django.contrib.sitemaps.views 然后使用站点地图创建字典

# urls.py

from django.contrib.sitemaps.views import sitemap, index
from app.sitemaps import StaticViewSitemap

# add as many as sitemap you need as one key
sitemaps = {
    "static" : StaticViewSitemap,
}
urlpatterns = [

    # sitemap.xml index will have all sitemap-......xmls index
    path('sitemap.xml', index, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.index'),

    # sitemap-<section>.xml here <section> will be replaced by the key from sitemaps dict
    path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]

在这里您将有两个站点地图 1. sitemaps.xml 2. sitemaps-static.xml 运行服务器打开 URL:http://localhost:8000/sitemap.xml

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <sitemap>
        <loc>http://127.0.0.1:8000/sitemap-static.xml</loc>
    </sitemap>
</sitemapindex>

Django 自动创建了站点地图索引,现在打开 URL: http: //127.0.0.1 :8000/sitemap-static.xml

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://localhost:8000/</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <url>
        <loc>http://localhost:8000/about-us</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <url>
        <loc>http://localhost:8000/our-story</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
</urlset>
于 2019-10-19T05:48:16.407 回答
1

对我来说,公认的答案是影响开发和测试周期速度,因为它使python manage.py命令运行得更慢——我在数据库中要做的事情比这个例子多一点。

以下是我为减轻影响所做的更改(适用于示例)。尚未对其进行战斗测试,但这似乎可以解决问题(Python3):

### sitemaps.py

class SitemapLookup():
    """
    Instantiated class replaces the dictionary of {'sitemap-section': Sitemap} for urls.py
    Speeds up application load time by only querying the DB when a sitemap is first requested.
    """

    def __init__(self):
        self.sitemaps = {}

    def __iter__(self):
        self._generate_sitemaps_dict()
        return self.sitemaps.__iter__()

    def __getitem__(self, key):
        self._generate_sitemaps_dict()
        return self.sitemaps[key]

    def items(self):
        self._generate_sitemaps_dict()
        return self.sitemaps.items()

    def _generate_sitemaps_dict(self):
        if self.sitemaps:
            return
        for section in Section.objects.all():
            info_dict = {
                'queryset': section.article_set.filter(is_published=True),
            }
            # dict key is provided as 'section' in sitemap index view
            self.sitemaps[section.name] = GenericSitemap(info_dict, priority=0.6)



### urls.py
from sitemaps import SitemapLookup

...
...
...

sitemaps = SitemapLookup()

urlpatterns += patterns('',
        (r'^sitemap.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
        (r'^sitemap-(?P<section>.+)\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)
于 2017-05-01T19:38:32.537 回答