BLOG

Sitemap in Django - Auto-generate sitemap.xml with Django in PythonAnywhere.

python

I will show you how to automatically generate sitemap.xml with PythonAnywhere django.

How to auto generate sitemap.xml in django in PythonAnywhere.

Add the following in settings.py.

SITE_ID = 1

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

Then add the following in urls.py.

*This is urls.py for the one with settings.py.

from django.contrib.sitemaps.views import sitemap
from .sitemaps import (ArticleSitemap,StaticSitemap)

sitemaps = {
    'Article': ArticleSitemap,
    'static': StaticSitemap,
}

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

Next, create a new sitemaps.py.

*Store in the same directory where settings.py is located.

from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from blog.models import Article

class ArticleSitemap(Sitemap):
    changefreq = "Always"
    priority = 1

    def items(self):
        return Article.objects.all()

    def location(self, obj):
        return reverse('blog:detail', args=[obj.slug])

    def lastmod(self, obj):
        return obj.updated_at

class StaticSitemap(Sitemap):
    changefreq = 'Always'
    priority = 1

    def items(self):
        return ['blog:index']

    def location(self, item):
        return reverse(item)

Next, open the Django admin page.

Since "Sites" is created in the Django admin page, Just change "example.com" to your own URL and you're done.

[Sitemap.xml] How to make it recognized by google crawler.

I will also introduce how to get Google's crawler to recognize the sitemap.

Execute the following command in the console of PythonAnywhere.

python manage.py ping_google /sitemap.xml

It's OK if there are no errors.

However, even if you upload a sitemap and send a ping, It may not be indexed.

I will show you how to solve it someday.

Next time, I will show you how to use robots.txt to teach sitemap.xml to the crawler.

  1. python
  2. Sitemap in Django - Auto-generate sitemap.xml with Django in PythonAnywhere.

AUTHOR

Almost 10 years have passed since I started learning web development. Learning web development has made my life more fulfilling. This is because the greatest benefit that can be obtained in the process of learning web development is that when you encounter difficulties, you acquire the attitude of actively searching for information to solve them on your own. And just as I learned a lot from the knowledge of my predecessors, I hope that by disseminating information in English, it will reach people around the world who want to learn web development. life is very short. I would be very happy if I could add even a little bit to your life by my outputting what I learned every day. Maybe the information is incorrect or outdated at times. I'll update when I find out.