Django 生成sitemap.xml文件

更多关注:http://www.mknight.cn/
要想生成sitemap.xml文件,则需要满足以下条件:

  • Add 'django.contrib.sitemaps' to your INSTALLED_APPS
    setting.
  • Make sure your TEMPLATES setting contains a DjangoTemplates backend whose APP_DIRS options is set to True. It’s in there by default, so you’ll only need to change this if you’ve changed that setting.
  • Make sure you’ve installed the sites framework
    .
    简单说,添加sitemaps,修改templates,检查sites.

设置models

class Article(models.Model):
    author = models.ForeignKey(User)
    title = models.CharField(max_length=200,unique=True)

    XXXXXXXXXXXXX
   #添加sites字段
    sites = models.ManyToManyField(Site)
   # 设置通用url 
   def get_absolute_url(self):
        return '/post/%s.html' % (self.id)

修改完成后,重新 makemigrations 和 migrate.

配置settings

add

添加 'django.contrib.sites'和 'django.contrib.sitemaps',”

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #增加
    'django.contrib.sites',
    'django.contrib.sitemaps',
    # other apps
    'compressor',
]

修改TEMPLATES,确保为True.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
         ..............

site

增加一行:

SITE_ID = 1

注意,此处的ID为,django_site表中的记录值

django_site

urls

引用

from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
from APP_Name import models

增加url

info_dict = {
    'queryset': models.Article.objects.all(),
    'date_field': 'published_date',
}

url(r'^sitemap\.xml$', sitemap,
        {'sitemaps': {'Earth': GenericSitemap(info_dict, priority=0.6)}},
        name='django.contrib.sitemaps.views.sitemap'),

info_dict 是设定请求的models,和发布日期;
下面的url指定请求方式。

验证

访问 http://localhost:8000/sitemap.xml

This XML file does not appear to have any style information associated with it. The document tree is shown below.


http://www.mknight.cn/post/31.html
2017-11-02
0.6


http://www.mknight.cn/post/32.html
2017-11-02
0.6


http://www.mknight.cn/post/33.html
2017-10-31
0.6


http://www.mknight.cn/post/34.html
2017-10-27
0.6


http://www.mknight.cn/post/35.html
2017-10-25
0.6


参考资料:
https://docs.djangoproject.com/en/1.11/ref/contrib/sitemaps/ https://docs.djangoproject.com/en/1.11/ref/contrib/sites/#module-django.contrib.sites
更多关注:http://www.mknight.cn/

你可能感兴趣的:(Django 生成sitemap.xml文件)