---
title: "djange自带的sitemap工具的使用"
author: "ice_cube"
date: "2010-07-21T16:14:21Z"
tags: []
categories: ["编程语言"]
slug: "djange-sitemap"
draft: false
lastmod: "2010-07-21T16:14:21Z"
id: 717998
url: "https://ice-cube.iteye.com/blog/717998"
---

最近用django(版本1.1.1)搭建了一个网站<http://www.ecgoo.net>，这是一个电子元器件国际交易平台，网站建设之初就很注重SEO的优化，因此生成网站站点地图，并向google提交是必不可少的。

查看了一下django文档，发现利用她自带的sitemap框架，只要简单的几步就能生成你想要的sitemap。

例如，想要将IC库存地址，如:<http://www.ecgoo.net/stock/ADG884BCPZ-REEL7.html> 编入sitemap中

1.在settings.py中添加sitemap框架app


```python

 'django.contrib.sitemaps', 

```


2.定制地图成员 

sitemaps.py

```python

from django.contrib.sitemaps import Sitemap
from django.conf import settings
from models import Roulette

class WitSitemap(Sitemap):
    '''
    Create Sitemaps for Wit 
    '''
    changefreq = "daily"
    priority = 0.5

    def items(self):
        return Roulette.objects.all()

    def location(self,obj):
        return "/stock/%s.html" % (obj.partno) #定制地图的url

```


其中Roulette是自己定义的IC型号类

3.在url.py中加入


```python

sitemaps = {
        'partno': WitSitemap(),
        }

urlpatterns = patterns('',
    (r'^sitemap.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
    (r'^sitemap-(?P<section>.+)\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)

```


注：sitemaps.views中有两个方法，index和sitemap

index生成的是主目录站点地图，格式如下:


```xml

<sitemapindex>
   <sitemap>
      <loc>
        http://www.ecgoo.net/sitemap-partno.xml
      </loc>
   </sitemap>
</sitemapindex>

```


sitemap生成的是具体的url，格式如下：


```xml

<urlset>
    <url>
        <loc>
            http://www.ecgoo.net/stock/admv.html
        </loc>
        <changefreq>daily</changefreq>
        <priority>0.5</priority>
    </url>
</urlset>

```


可以通过修改上面两个方法的源码来修改xml，得到你所需要的url格式