Introduction
A sitemap is an important part of any website. Even though today there are instant indexing technologies such as IndexNow, a sitemap helps search engines learn about the structure of your website and the pages that would be nice to index.
You have two options for how to add a map to your website. The first is to write it manually (I don't recommend it). The second is to generate it using Django's built-in utilities. The second method, unlike the first, assumes that once you write it, you will never remember it again. Here.
Develop a sitemap
The first thing to do is to create a sitemap.py file in any suitable place. In my case, I usually create it in the Backend application. I think it makes sense. From now on, we will work only in the sitemap.py file. As usual, I will dump all the code at once; the explanation will be after.
Here are 3 cases of using sitemaps. The first, ArticleSitemap, collects all the articles into the sitemap. The second, ArticlePaginationSitemap, works with pagination pages.
And the third class, StaticSitemap, works with static pages. That is, pages that do not change and are not generated in hundreds. I'm talking about contact pages, author and home pages, and, in general, single and unique pages.
The Sitemap class has 3 main (but there are others), in my opinion, methods that can be useful to everyone:
- items - determines what will be returned and how many elements will be returned in the list.
- location - returns which path to return
- lastmod - returns the date of the last update of content, article, category.
Furthermore, for StaticSitemap, I use a modifier such as i18n=True. I do this because I have these pages in several translation options. Therefore, for example, it will return not http://website.com/article1, but http://website.com/ru/article1 + http://website.com/en/article1.
Connect a sitemap
After you have written your Sitemap classes, you will need to connect them in the main urls.py, where the application URLs are connected. And, of course, to connect a default django app for rendering sitemaps in settings.py. In the urls.py file:
In the settings.py file:
We import the previously created Sitemap classes, plus a view for our sitemaps. Afterward, we create a dictionary for all the created classes and connect them to urlpatterns. Yes, we connect them not in urlpatterns = + i18n_patterns, because according to the precepts of search engines, sitemaps should be in the root directory.
Don't forget to add a link to the sitemap in the robots.txt file:
Conclusion
I would like to add that the possibilities of generating sitemaps are not limited to this. You can generate several at once and combine them into an index sitemap. Or you can generate robots.txt in django and combine it with the sitemap without manual intervention. In any case, for a more in-depth acquaintance with the topic, I recommend reading the official documentation.