The tutorial is from the textbook ‘Django 3 by example’, Chapter 3 Extending your blog application
Here is the sitemaps.py of the blog app. The project has 2 apps, one, the polls app from Writing your first app on here and the blog app from the textbook.
from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.9
def items(self):
return Post.published.all()
def lastmod(self, obj):
return obj.updated
I added a SITE_ID as instructed (though, I don’t know what the SITE_ID really does), added django.contrib.sites and django.contrib.sitemaps to the INSTALLED_APPS
Here is my project’s urls.py, not the blog app’s urls.py
from django.contrib import admin
from django.urls import include, path
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
sitemaps={ 'posts': PostSitemap }
urlpatterns = [
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},\
name='django.contrib.sitemaps.views.sitemap'),
path('admin/', admin.site.urls),
path('polls/', include('polls.urls', namespace="polls")),
path('blog/', include('blog.urls', namespace='blog'))
]
Here is the base.html (my base template)
{% load blog_tags %}
{% load static %}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog.css" %}" type="text/css" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2><a href="{% url 'blog:post_list' %}">My Blog</a></h2>
<p>This is my blog, I have written {% total_post %} posts so far.</p>
<p><a href="{% url "blog:post_feed" %}">Subcribe to my feed</a></p>
<h3>Latest Posts</h3>
{% show_latest_posts 3 %}
<h3>Most Commented Posts</h3>
{% get_most_commented_posts as most_commented_posts %}
<ul>
{% for post in most_commented_posts %}
<li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
</div>
</body>
</html>
Here is the post_list view from my views.py that renders the page and (which from the view passed to path in the project’s urls.py is not the one rendering the sitemap)
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3) # 3 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request,
'blog/post/list.html',
{'page': page,
'posts': posts,
'tag': tag})