В корневом urls.py:
...
from django.views.generic import TemplateView # для вывода policy, robots и т.д.
from shop_app import views # для вывода sitemap
urlpatterns = [
path('', include('shop_app.urls')),
path('sitemap.xml', views.SitemapXmlView.as_view()),
path('robots.txt', TemplateView.as_view(template_name='doc/robots.txt', content_type='text/plain')),
path('policy.txt', TemplateView.as_view(template_name='doc/policy.txt', content_type='text/plain')),
path('terms.txt', TemplateView.as_view(template_name='doc/terms.txt', content_type='text/plain')),
path('admin/', admin.site.urls),
...
Код из views.py:
...
class SitemapXmlView(TemplateView):
"""АВТОГЕНЕРАТОР SITEMAPxml"""
template_name = 'sitemapxml.html'
content_type = 'application/xml'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['category_list'] = Category.objects.all()
context['sub_category_list'] = SubCategory.objects.all()
context['product_list'] = Product.objects.filter(public=True).all()
return context
...
И сам файл sitemapxml.html:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>{{ request.scheme }}://{{ request.get_host }}</loc>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
{% for object in category_list %}
<url>
<loc>{{ request.scheme }}://{{ request.get_host }}{{ object.get_absolute_url }}</loc>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
{% endfor %}
{% for object in sub_category_list %}
<url>
<loc>{{ request.scheme }}://{{ request.get_host }}{{ object.get_absolute_url }}</loc>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
{% endfor %}
{% for object in product_list%}
<url>
<loc>{{ request.scheme }}://{{ request.get_host }}{{ object.get_absolute_url }}</loc>
<lastmod>{{ object.update|date:"Y-m-d" }}</lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
{% endfor %}
</urlset>