Evgenii Legotckoi
Evgenii LegotckoiSept. 24, 2016, 7:55 a.m.

Django - Tutorial 008. Adding a Sitemap file on a site based on Django

RSS is added, but you need to help search engines index your site. And this is done with the help of Sitemap files that describe the structure of the site. Django provides a ready-made classes and mechanisms for the formation of Sitemap files, moreover it is possible to form the core of embedded Sitemap, ie subsidiaries Sitemap files, which will be responsible for certain areas. Django also has the ability to cache Sitemap files, which is useful in the event that there are tens of thousands of links on the site.

From the perspective of the current state of EVILEG COM site will be formed three Sitemap file, which will be invested in a major:

  • Main Sitemap permanent pages and home page of the site;
  • Sitemap sections;
  • Sitemap articles.

Configuration of settings.py

First we configure site configuration file to be able to work with Sitemap.

SITE_ID = 1

INSTALLED_APPS = [
    ...
    'django.contrib.sitemaps',
    'django.contrib.sites',
    ...
]

SITE_ID necessary to identify a resource in a database. If you will not be added this parameter, the site admin will not prescribe the url of your website for which is done Sitemap . Sitemap for search engines simply will not emerge then. After the site setting appears in the admin area, then you need to register the domain of your site, or in Sitemap url will start with example.com.

With regard INSTALLED_APPS , then all should be clear. The first module is responsible for handling sitemaps, and the second module is responsible for handling directly SITE_ID parameter in a database.

Configuration of urls.py of a main application of a site

Speaking about the main application, I mean the application, which is located in the settings.py file folder. In the current implementation, all url Sitemap Site urls.py described in the file is just the most basic of applications throughout the site.

Let's see, that is responsible for what.

from django.contrib.sitemaps import views as sitemap_views    # view 
from django.contrib.sitemaps import GenericSitemap            # Template class for Sitemap
from django.views.decorators.cache import cache_page          # cache decorator

from knowledge import models as knowledge_models     # Models of the articles and sections which will form Sitemap
from home.sitemap import HomeSitemap                 # Static Sitemap for relatively permanent pages

# Object partition map. It just takes all the objects from the database, 
# as well as the eponymous field in the model climbs the date of the last modification
sitemap_sections = {
    'queryset': knowledge_models.Section.objects.all(),
    'date_field': 'section_lastmod',
}

# But it is more interesting with articles. Here are collected only those articles that have been published. 
# And for this you need to write a special manager
sitemap_articles = {
    'queryset': knowledge_models.Article.objects.article_status(),
    'date_field': 'article_date',
}

# We form an object with all the cards and assign them names
sitemaps = {
    'sections': GenericSitemap(sitemap_sections, priority=0.5),
    'articles': GenericSitemap(sitemap_articles, priority=0.5),
    'home': HomeSitemap
}

# Templates the URL, note, it is given caching cache_page (86400)
# The first pattern will form the basic map of the site, which will indicate the URL of subsidiaries,
# 'sitemap-sections', 'sitemap-articles', 'sitemap-home'
# Notice that their name in common with the names of the parameters in the object sitemaps?
urlpatterns += [
    url(r'^sitemap\.xml$', cache_page(86400)(sitemap_views.index), {'sitemaps': sitemaps}),
    url(r'^sitemap-(?P<section>\w+)\.xml$', cache_page(86400)(sitemap_views.sitemap), {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'),
]

Static Sitemap

To begin with we shall understand with the static Sitemap, which means that it will be transferred to the page like a contact page, home page, offers, etc. In my case, it is in the home application.

from django.contrib import sitemaps
from django.urls import reverse     


class HomeSitemap(sitemaps.Sitemap):
    priority = 0.5        
    changefreq = 'daily'   

    # The method returns an array with url
    def items(self):
        return ['home:index', 'home:contacts']

    # The method of direct extraction url from Template
    def location(self, item):
        return reverse(item)

Section model

In order to form the url of Sitemap from model necessary to have get_absolute_url method in the model. In general, I recommend this method to add a bit earlier, because they are very convenient to use both templates and elsewhere in the code.

class Section(models.Model):

    ...

    section_url = models.CharField('URL Раздела', max_length=50)

    def get_absolute_url(self):
        return reverse('knowledge:section', kwargs={'section': self.section_url})

As you can see, the model contains a section of the address, which is inserted into the template 'knowledge: section'

Article model

Here is the same as that of the sections except that added ArticleManager , which is a substitute for objects, to extend the set of methods, for example by article_status , in which are collected only those articles that have been published. And this method instead of the method of all, you can see in urls.py file cards when forming articles.

class ArticleManager(models.Manager):
    use_for_related_fields = True

    def article_status(self):
        return self.get_queryset().exclude(article_status=False)


class Article(models.Model):

    ...

    article_section = models.ForeignKey(Section)

    objects = ArticleManager()    

    def get_absolute_url(self):
        return reverse('knowledge:article', kwargs={'section': self.article_section.section_url,
                                                    'article_id': self.id})

For Django I recommend VDS-server of Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 2:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 2:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 2:35 p.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 3:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 4:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 12:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 2:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks