Chapter 13 · 10 min read
Capstone: The Finished Blog
Capstone: The Finished Blog
You now have every ingredient of a classic Django site. In this chapter you tidy the blog into its final form by adding pagination and success messages, review the whole project layout, and plan your own extensions. The complete final source code is listed in the Reference chapter named Capstone Source Code.
What you will learn
- How the pieces of the blog fit together.
- How to add pagination with
paginate_by. - How to show one-time messages with the messages framework.
- How to plan and build your own extensions.
The finished layout
myblog/
manage.py
db.sqlite3
config/
settings.py
urls.py
...
blog/
models.py
forms.py
views.py
urls.py
admin.py
tests.py
migrations/0001_initial.py
static/blog/style.css
templates/blog/base.html
templates/blog/post_list.html
templates/blog/post_detail.html
templates/blog/post_form.html
templates/registration/login.html
templates/registration/signup.html
Follow one request through it. A visitor opens /post/3/:
config/urls.pyfinds no match foradmin/oraccounts/, so it hands the address toblog.urls.blog/urls.pymatchespost/<int:pk>/and callsPostDetailView.- The view asks the
Postmodel for the row withpk=3. - The view renders
blog/post_detail.html, which extendsblog/base.htmland loadsstyle.csswith thestatictag. - The response goes back to the browser.
Step by step
1. Final views
Replace blog/views.py with the final version. It adds paginate_by and a success message to what you already wrote:
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView, DetailView, ListView, UpdateView
from .forms import PostForm
from .models import Post
class PostListView(ListView):
model = Post
paginate_by = 5
queryset = Post.objects.filter(published=True).select_related("author")
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
form_class = PostForm
def form_valid(self, form):
form.instance.author = self.request.user
messages.success(self.request, "Post created!")
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
form_class = PostForm
def test_func(self):
return self.get_object().author == self.request.user
class SignUpView(CreateView):
form_class = UserCreationForm
template_name = "registration/signup.html"
success_url = reverse_lazy("login")
paginate_by = 5 makes ListView split results into pages of five and read the page number from ?page=2. It adds page_obj, paginator and is_paginated to the context.
2. Show messages in the base template
In base.html, directly below the closing </nav> tag, add:
{% if messages %}
<ul class="messages">
{% for message in messages %}<li>{{ message }}</li>{% endfor %}
</ul>
{% endif %}
The messages framework stores a message in the session and shows it once on the next page. messages.success() is one of several levels (debug, info, success, warning, error).
3. Page links in the list template
In post_list.html, just before {% endblock %}, add:
{% if is_paginated %}
<p>
{% if page_obj.has_previous %}<a href="?page={{ page_obj.previous_page_number }}">Newer</a>{% endif %}
Page {{ page_obj.number }} of {{ paginator.num_pages }}
{% if page_obj.has_next %}<a href="?page={{ page_obj.next_page_number }}">Older</a>{% endif %}
</p>
{% endif %}
Check it works
- With more than five published posts, the home page shows
Page 1 of 2and a working Older link. - Creating a post shows the green
Post created!box on the detail page. - A visitor who is not logged in can read posts but is redirected when opening
/post/new/. - In the admin you can manage users and posts.
Extension ideas
Pick one and build it yourself. After every model change run makemigrations and migrate.
| Idea | New concepts |
|---|---|
| Comments | A Comment model with a ForeignKey to Post, a form, and a list under each post |
| Categories | A Category model, a ManyToManyField on Post, and a page per category |
| Delete posts | DeleteView with an author-only test |
| Search | request.GET, icontains filters |
| Slugs in URLs | A SlugField and <slug:slug> converters |
| Markdown | Render post text safely |
Exercises with solutions
Exercise 1: comments model
Add a Comment model and show comments on the detail page.
Solution. In blog/models.py:
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["created"]
def __str__(self):
return f"Comment by {self.author} on {self.post}"
Run python manage.py makemigrations blog and python manage.py migrate. Register it in admin.py with admin.site.register(Comment). In post_detail.html:
<h2>Comments</h2>
{% for comment in post.comments.all %}
<p><strong>{{ comment.author.username }}</strong>: {{ comment.text }}</p>
{% empty %}
<p>No comments yet.</p>
{% endfor %}
Exercise 2: page size
Make the page size 3 and confirm the link behaviour.
Solution. Change paginate_by = 3. With seven published posts you get three pages; the Newer link appears from page 2 onward and the Older link until page 3.
Exercise 3: warning message
Show a warning message when an author edits their post.
Solution. Override form_valid in PostUpdateView:
def form_valid(self, form):
messages.warning(self.request, "Post updated.")
return super().form_valid(form)
Common mistakes
paginate_bywithout page links in the template. Extra pages exist, but nobody can reach them.- Messages not showing. The
{% if messages %}block must be in the base template that every page extends. - Changing models without
makemigrationsandmigrate. - Building everything at once. Add one feature, test it, then commit it.
- Forgetting
select_relatedwhen adding relations. Check the page for extra queries.
Key takeaways
- The blog combines URLs, views, templates, models, forms, authentication and the admin.
paginate_bygives pagination with almost no code.- The messages framework shows one-time notices.
- Extend the project one small feature at a time.
Official links
- Pagination: https://docs.djangoproject.com/en/6.1/topics/pagination/
- Messages framework: https://docs.djangoproject.com/en/6.1/ref/contrib/messages/
