Django provides a useful shortcut that allows you to create a sitemap for generic views without having to define your own Sitemap class. Instead, you can use the django.contrib.sitemaps.GenericSitemap class.
The GenericSitemap class builds a Sitemap class from the same info dictionary that you pass the generic view. Instead of defining a list() function, the info dictionary needs to contain a queryset entry containing the list of objects. Instead of lastmod, GenericSitemap uses the date_field entry if one is defined in the dictionary. The priority and changefreq values can be specified as arguments when you create an instance of GenericSitemap.
The following is an example of using the GenericSitemap class to build a sitemap for a generic view:
from django.contrib.sitemaps import GenericSitemap from django.views.generic import date_based log_info_dict = { 'queryset' : log.objects.all(), 'date_field' : 'last_modified', } sitemaps = { 'log': GenericSitemap(log_info_dict, priority=0.2, changefreq='daily'), } urlpatterns += patterns('', (r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}), (r'^generic/log_arch/$',date_based.archive_index, log_info_dict), )
Did you Know?
You can also create sitemaps for flatpages on your website. The location is the only attribute attached to the object in the sitemap. The lastmod, changefreq, and priority attributes are not added. To add flatpages to the sitemap, simply add the django.contrib.sitemaps.FlatPageSitemap class to the sitemaps dictionary:
from django.contrib.sitemaps import FlatPageSitemap sitemaps = { 'flat': FlatPageSitemap, }
Try It Yourself: Create and Enable a Sitemap for Generic ViewsIn this section, you will create and enable a GenericSitemap class that will generate a sitemap for the blog_details generic view you created in Hour 12, "Utilizing Generic Views." Follow these steps to create and enable the sitemap:
Listing 21.3. The Imports, blog_detail_info Dictionary, and Sitemap Sections of the iFriends/urls.py File
Listing 21.4. The Blog Class Definition in the iFriends/People/models.py File
|