pythondjangodjango-sitesdjango-sitemaps

Django 1.6: What should be the location of the sitemap.py file?


I want to implement django sitemaps but I'm little confused about where to put the sitemaps.py file and which urls.py file should i modify to include:

url(r'^sitemap.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),

Shall I put the above line in project(mysite) urls.py file or the app(sampleapp1) urls.py file?


Solution

  • You create sitemaps within the apps of your project (the ones you need sitemaps), documentation doesn't state what and where because you are free to do as you like, you only need to register them in a dictionary which is passed in the url. For example, you have a your_project which has a blog app:

    your_project
      - blog
        - models.py
        - views.py
        - ...
        - sitemap.py
    

    In your sitemap.py:

    from django.contrib.sitemaps import Sitemap
    from blog.models import Entry
    
    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
    

    Then in your urls.py (main urls.py of your project):

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

    You repeat the same for every sitemap you need, if your project is big (many apps) it would be wise to use different sitemaps per app, then in your urls.py:

    ...
    
    from blog.sitemap import BlogSitemap
    from fooapp.sitemap import FooSitemap
    from barapp.sitemap import BarSitemap
    
    sitemaps = {
        'blog':BlogSitemap,
        'foo':FooSitemap,
        'bar':BarSitemap,
    }