Skip to main content
 首页 » 编程设计

python之如何将主页添加到 Django 站点地图

2025年05月04日39jackei

给定站点地图类的站点地图在该位置生成站点地图,example.com/sitemap.xml

从 django.contrib.sitemaps 导入站点地图 从 blog.models 导入条目 对于给定的 Sitemap 类,

class BlogSitemap(Sitemap): 
    changefreq = "never" 
    priority = 0.5 
 
    def items(self): 
        return Entry.objects.filter(is_draft=False) 
 
    def lastmod(self, obj): 
        return obj.pub_date 

生成的站点地图包含Blog模型中的所有对象,但不包含Queryset之外的内容,如何将主页添加到站点地图?

网址

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

请您参考如下方法:

创建一个 sitemap for static views :

class StaticViewSitemap(sitemaps.Sitemap): 
    priority = 0.5 
    changefreq = 'daily' 
 
    def items(self): 
        return ['home'] 
 
    def location(self, item): 
        return reverse(item) 

这假设您有名称为“home”的主页的 url 模式

url(r'^$', views.homepage, name="home"), 

然后将 StaticViewSitemap 添加到 urls.py 中的 sitemaps 字典中。

sitemaps = { 
    'blog': BlogSitemap, 
    'static': StaticViewSiteMap, 
}