Serhii
Serhii

Reputation: 96

How to create sitemap for multilingual site on django

Sorry but I need help. I have 2 languages on the site (uk, en) How I can do two individual sitemap for site? That they have a prefix in url and each contained only url that related only to the language selected. For example for two routes: /uk/sitemap.xml /en/sitemap.xml

I try this:

from django.contrib.sitemaps import Sitemap
from beerpost.models import Beerpost
from django.urls import reverse

class BeerpostSitemap(Sitemap):
    i18n = True
    priority = 0.5
    changefreq = 'daily'

    def items(self):
        return Beerpost.objects.filter(is_active=True)

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

But I have 1 sitemap witch included all links with two languages. After I try delete

i18n = True

and in url.py added

from django.conf.urls.i18n import i18n_patterns
urlpatterns += i18n_patterns(
  path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'),
)

After I got what I want: separate routes in my sitemaps, but this routes don't include prefix (en or ua) how I can add his there? I have this: /uk/sitemap.xml

<url>
<loc>
https://rate-beer.info/lvivske-lvivske-svitle-rozlivne/8831
</loc>
<lastmod>2019-09-19</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>

/en/sitemap.xml

<url>
<loc>
https://rate-beer.info/lvivske-lvivske-light-draft-beer/8831
</loc>
<lastmod>2019-09-19</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>

How I can get this with "/en/"? /en/sitemap.xml

<url>
<loc>
https://rate-beer.info/en/lvivske-lvivske-light-draft-beer/8831
</loc>
<lastmod>2019-09-19</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>

Upvotes: 1

Views: 850

Answers (1)

Serhii
Serhii

Reputation: 96

I found decision:

from django.contrib.sitemaps import Sitemap
from beerpost.models import Beerpost


class BeerpostSitemap(Sitemap):
    priority = 0.5
    changefreq = 'daily'
    def items(self):
        beers = Beerpost.objects.filter(is_active=True)
        for b in beers:
            if  b.slug_uk:
                b.slug_uk = str('uk/')+b.slug_uk
            if b.slug_en:
                b.slug_en = str('en/')+b.slug_en
        return beers

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

and sitemap now have prefix in url

Upvotes: 0

Related Questions