Skip to main content
 首页 » 编程设计

python之Django 站点地图静态页面

2024年10月17日27kevingrace

我有一个网站,其中包含定期添加和删除内容的动态页面。除此之外,该网站还有始终存在的静态页面,例如/、/about、/how-it-works 等。 我已将我的 sitemaps.py 文件配置为加载站点地图中的所有动态内容页面。

站点地图.xml

... 
<url> 
<loc> 
https://www.mywebsite.com/record?type=poem&id=165 
</loc> 
<changefreq>weekly</changefreq> 
<priority>0.5</priority> 
</url> 
... 

站点地图.py

from django.contrib.sitemaps import Sitemap 
 
from website.models import Content 
 
class MySitemap(Sitemap): 
    changefreq = "weekly" 
    priority = 0.5 
 
    def items(self): 
        return Content.objects.all() 

模型.py

class Content(models.Model): 
    content_type = models.CharField(max_length=255) 
    ... 
    def get_absolute_url(self): 
        return '/record?type=' + self.content_type + '&id=' + str(self.id) 

如何在站点地图中添加这些静态页面(/、/about 等)? 谢谢!

请您参考如下方法:

经过一番搜索,我找到了这个 Django Sitemaps and "normal" views .按照马特奥斯汀的回答,我能够实现我想要的。我会将我所做的留在此处以供将来引用。

站点地图.py

from django.contrib.sitemaps import Sitemap 
from django.core.urlresolvers import reverse 
 
from website.models import Content 
 
class StaticSitemap(Sitemap): 
    """Reverse 'static' views for XML sitemap.""" 
    changefreq = "daily" 
    priority = 0.5 
 
    def items(self): 
        # Return list of url names for views to include in sitemap 
        return ['landing', 'about', 'how-it-works', 'choose'] 
 
    def location(self, item): 
        return reverse(item) 
 
class DynamicSitemap(Sitemap): 
    changefreq = "daily" 
    priority = 0.5 
 
    def items(self): 
        return Content.objects.all() 

urls.py

from website.sitemaps import StaticSitemap, DynamicSitemap 
sitemaps = {'static': StaticSitemap, 'dynamic': DynamicSitemap} 
 
urlpatterns = [ 
    ... 
    url(r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}), 
]