如何在Django框架中实现Google News Sitemap标准?
在Django中实现Google News Sitemap标准的方法
要实现符合Google News规范的Sitemap,你可以基于Django自带的sitemap框架进行扩展,以下是具体步骤:
1. 定义新闻模型(已有可跳过)
假设你用NewsArticle模型存储新闻内容,核心字段需包含标题、发布日期、永久链接:
# models.py from django.db import models from django.utils import timezone class NewsArticle(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) publication_date = models.DateTimeField(default=timezone.now) # 可按需添加正文、分类等其他字段 def get_absolute_url(self): return f"/news/{self.slug}/" # 生成新闻永久链接
2. 创建自定义News Sitemap类
继承Django的Sitemap类,添加Google News所需的自定义属性,同时过滤出符合要求的内容(Google仅接受最近90天的新闻):
# sitemaps.py from django.contrib.sitemaps import Sitemap from .models import NewsArticle from django.utils import timezone class NewsSitemap(Sitemap): protocol = 'https' # 根据站点实际协议选择http/https changefreq = 'daily' priority = 0.9 def items(self): # 仅返回最近90天发布的新闻 ninety_days_ago = timezone.now() - timezone.timedelta(days=90) return NewsArticle.objects.filter(publication_date__gte=ninety_days_ago).order_by('-publication_date') def lastmod(self, obj): return obj.publication_date # Google News 必填字段 def news_publication_name(self, obj): return "你的新闻站点名称" # 替换为实际站点名称 def news_publication_language(self, obj): return "zh" # 替换为站点语言(ISO 639-1格式,如en、zh-CN) def news_title(self, obj): return obj.title def news_publication_date(self, obj): return obj.publication_date.strftime('%Y-%m-%d')
3. 配置URL路由
在项目urls.py中添加News Sitemap的路由,指定自定义模板:
# urls.py from django.contrib.sitemaps.views import sitemap from .sitemaps import NewsSitemap sitemaps = { 'news': NewsSitemap, } urlpatterns = [ # 其他路由配置... path('sitemap-news.xml', sitemap, {'sitemaps': sitemaps, 'template_name': 'sitemaps/news_sitemap.xml'}, name='news-sitemap'), ]
4. 编写自定义XML模板
创建符合Google News规范的XML模板,添加news命名空间并渲染自定义字段:
<!-- templates/sitemaps/news_sitemap.xml --> <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"> {% for url in urlset %} <url> <loc>{{ url.location }}</loc> {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %} {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %} {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %} <news:news> <news:publication> <news:name>{{ url.news_publication_name }}</news:name> <news:language>{{ url.news_publication_language }}</news:language> </news:publication> <news:publication_date>{{ url.news_publication_date }}</news:publication_date> <news:title>{{ url.news_title }}</news:title> </news:news> </url> {% endfor %} </urlset>
额外注意事项
- Google News要求Sitemap仅包含最近90天内的内容,
items方法中的时间过滤不可省略 - 语言代码需遵循ISO 639-1标准,如中文用
zh或zh-CN,英文用en - 若需添加更多Google News支持的字段(如关键词、股票代码),只需在
NewsSitemap类中新增对应方法,并在模板中渲染即可
内容的提问来源于stack exchange,提问作者Jack Gruber
相关产品推荐
相关产品推荐

