article

Friday, May 22, 2020

Django How to create Sitemaps for the blog application


Django How to create Sitemaps for the blog application

sitemap is an XML file that informs search engines such as Google, the pages of your website, their relevance, and how frequently they are updated.


sitemap plays a crucial role in modern SEO (Search Engine Optimization).

In this article, we will learn how to create sitemaps for the blog application

Installation
Add 'django.contrib.sitemaps' in INSTALLED_APPS setting setting.py
INSTALLED_APPS += ( 'django.contrib.sitemaps',)

Part 1 : Django Build a blog application with bootstrap and Automatically Generate slugs

https://tutorial101.blogspot.com/2020/05/django-build-blog-application-with.html

Part 2 : Django Build a blog application Part 2 with WYSIWYG Editor Pagination and Comments


https://tutorial101.blogspot.com/2020/05/django-build-blog-application-part-2.html




 
#models.py
from django.db import models
 
from django.contrib.auth.models import User
from django.utils.text import slugify

STATUS = (
    (0,"Draft"),
    (1,"Publish")
)

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='myapp_post')
    updated_on = models.DateTimeField(auto_now= True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)
 
    class Meta:
        ordering = ['-created_on']

    def __str__(self):
        return self.title
  
    def get_absolute_url(self):
        from django.urls import reverse
        return reverse("post_detail", kwargs={"slug": str(self.slug)})
  
    class Meta:  
        db_table = "myapp_post"
  
    def save(self, *args, **kwargs):
        value = self.title
        self.slug = slugify(value, allow_unicode=True)
        super().save(*args, **kwargs)
create a new file sitemaps.pyand add the following
 
#sitemaps.py
from django.contrib.sitemaps import Sitemap
from myapp.models import Post

class PostSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.8

    def items(self):
        return Post.objects.filter(status=1)

    def lastmod(self, obj):
        return obj.updated_on
optional changefreq and priority attributes indicate the change frequency of post

Possible values for changefreq, whether you use a method or attribute, are:

‘always’
‘hourly’
‘daily’
‘weekly’
‘monthly’
‘yearly’
‘never’

Sitemap.py

from django.contrib.sitemaps.views import sitemap
from myapp.sitemaps import PostSitemap


sitemaps = {
    "posts": PostSitemap,
}

urlpatterns = [
        ..........
    path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),
        .........
]

run the server and visit http://127.0.0.1:8000/sitemap.xml

To explore more visit – https://docs.djangoproject.com/en/3.0/ref/contrib/sitemaps/

Related Post