Project: Build a Blog
Time to bring everything together. In this project you'll build Kuza Blog, a complete blog with published and draft posts, an admin for writers, a paginated home page, post pages with readable URLs and a comment form for readers. It uses models, the admin, views, URLs, templates, static files and forms from across the series.
What you'll build
- A
Postmodel with title, URL slug, author, body, draft/published status and dates. - A
Commentmodel linked to each post. - An admin where writers create posts, with slugs filled in automatically and comments shown inline.
- A home page listing published posts, newest first, five per page.
- A post page at an address like
/five-free-places-to-study-in-nairobi/with comments and a comment form. - A shared base template and a small stylesheet.
Step 1: Set up the project
Start in a fresh folder, separate from Campus Events (see Installing Django if you need a reminder):
mkdir kuza-blog cd kuza-blog python -m venv .venv .venv\Scripts\activate # macOS/Linux: source .venv/bin/activate python -m pip install "django~=5.2.0" django-admin startproject blogsite . python manage.py startapp blog
Register the app, add a project templates folder and set the time zone:
blogsite/settings.py (changed parts only)
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"blog",
]
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
TIME_ZONE = "Africa/Nairobi"
Step 2: Write the models
blog/models.py
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Post(models.Model):
class Status(models.TextChoices):
DRAFT = "DF", "Draft"
PUBLISHED = "PB", "Published"
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts"
)
body = models.TextField()
status = models.CharField(max_length=2, choices=Status, default=Status.DRAFT)
published_at = models.DateTimeField(default=timezone.now)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["-published_at"]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("blog:post_detail", args=[self.slug])
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
name = models.CharField(max_length=80)
body = models.TextField()
approved = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["created_at"]
def __str__(self):
return f"Comment by {self.name} on {self.post}"
Design choices worth noticing:
StatususesTextChoices, so drafts can be written and saved without appearing on the site.slugis unique, so it can identify a post in the URL instead of a number.ordering = ["-published_at"]shows the newest posts first.- Deleting a post deletes its comments (
CASCADE), and comments can be hidden by un-tickingapproved. See Model Relationships.
Step 3: Migrate and create a superuser
python manage.py makemigrations
python manage.py migrate python manage.py createsuperuser
migrate prints a line for each of Django's built-in migrations and ends with your own, including Applying blog.0001_initial... OK. For this walkthrough, the superuser is called wanjiru.
Step 4: Set up the admin
blog/admin.py
from django.contrib import admin
from .models import Comment, Post
class CommentInline(admin.TabularInline):
model = Comment
extra = 0
fields = ["name", "body", "approved"]
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ["title", "author", "status", "published_at"]
list_filter = ["status", "published_at"]
search_fields = ["title", "body"]
prepopulated_fields = {"slug": ["title"]}
date_hierarchy = "published_at"
inlines = [CommentInline]
def get_changeform_initial_data(self, request):
return {"author": request.user} # new posts default to the logged-in writer
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ["name", "post", "approved", "created_at"]
list_filter = ["approved"]
actions = ["hide_comments"]
@admin.action(description="Hide selected comments")
def hide_comments(self, request, queryset):
queryset.update(approved=False)
prepopulated_fields fills in the slug as you type the title, so "Five free places to study in Nairobi" becomes five-free-places-to-study-in-nairobi.
Step 5: Create the comment form
blog/forms.py
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ["name", "body"]
labels = {"name": "Your name", "body": "Comment"}
widgets = {"body": forms.Textarea(attrs={"rows": 3})}
Only name and body are listed, so readers can't set post or approved themselves (see Model Forms).
Step 6: Write the views
A class-based ListView handles the paginated home page. The post page needs to show a post and process a form, so a function view keeps that logic easy to follow.
blog/views.py
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect, render
from django.views.generic import ListView
from .forms import CommentForm
from .models import Post
class PostListView(ListView):
queryset = Post.objects.filter(status=Post.Status.PUBLISHED).select_related("author")
context_object_name = "posts"
paginate_by = 5
template_name = "blog/post_list.html"
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug, status=Post.Status.PUBLISHED)
comments = post.comments.filter(approved=True)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
messages.success(request, "Thanks! Your comment has been posted.")
return redirect(post)
else:
form = CommentForm()
context = {"post": post, "comments": comments, "form": form}
return render(request, "blog/post_detail.html", context)
Filtering by status=PUBLISHED in both views means a draft's URL returns 404 even if someone guesses it.
Step 7: Connect the URLs
blog/urls.py
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.PostListView.as_view(), name="post_list"),
path("<slug:slug>/", views.post_detail, name="post_detail"),
]
blogsite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("blog.urls")),
]
The admin route comes first, so /admin/ is never mistaken for a post slug.
Step 8: Build the templates and stylesheet
templates/base.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Kuza Blog{% endblock %}</title>
<link rel="stylesheet" href="{% static 'blog/style.css' %}">
</head>
<body>
<header>
<a class="logo" href="{% url 'blog:post_list' %}">Kuza Blog</a>
</header>
<main>
{% for message in messages %}
<p class="message">{{ message }}</p>
{% endfor %}
{% block content %}{% endblock %}
</main>
<footer><p>Made with Django</p></footer>
</body>
</html>
blog/templates/blog/post_list.html
{% extends "base.html" %}
{% block content %}
<h1>Latest posts</h1>
{% for post in posts %}
<article class="card">
<h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
<p class="meta">{{ post.published_at|date:"j M Y" }} · by {{ post.author.username }}</p>
<p>{{ post.body|truncatewords:12 }}</p>
</article>
{% empty %}
<p>No posts yet. Check back soon!</p>
{% endfor %}
{% if page_obj.has_other_pages %}
<nav class="pagination">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">Newer posts</a>
{% endif %}
<span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">Older posts</a>
{% endif %}
</nav>
{% endif %}
{% endblock %}
blog/templates/blog/post_detail.html
{% extends "base.html" %}
{% block title %}{{ post.title }} | {{ block.super }}{% endblock %}
{% block content %}
<article>
<h1>{{ post.title }}</h1>
<p class="meta">{{ post.published_at|date:"j M Y" }} · by {{ post.author.username }}</p>
{{ post.body|linebreaks }}
</article>
<section>
<h2>{{ comments|length }} comment{{ comments|length|pluralize }}</h2>
{% for comment in comments %}
<div class="comment">
<strong>{{ comment.name }}</strong>
<span class="meta">{{ comment.created_at|date:"j M Y, H:i" }}</span>
{{ comment.body|linebreaks }}
</div>
{% empty %}
<p>Be the first to comment.</p>
{% endfor %}
</section>
<section>
<h2>Leave a comment</h2>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Post comment</button>
</form>
</section>
<p><a href="{% url 'blog:post_list' %}">Back to all posts</a></p>
{% endblock %}
blog/static/blog/style.css
body { font-family: system-ui, sans-serif; max-width: 720px; margin: 0 auto; padding: 0 16px; line-height: 1.6; }
header { padding: 16px 0; border-bottom: 2px solid #1a7f5a; }
.logo { font-weight: 700; font-size: 1.4rem; color: #1a7f5a; text-decoration: none; }
.card, .comment { border: 1px solid #ddd; border-radius: 8px; padding: 12px 16px; margin: 12px 0; }
.meta { color: #666; font-size: 0.9rem; }
.message { background: #e6f4ee; padding: 8px 12px; border-radius: 6px; }
textarea, input { width: 100%; padding: 6px; }
Step 9: Run it and try it out
python manage.py runserver
- Log in at
http://127.0.0.1:8000/admin/aswanjiru. - Add a post titled "How I saved my first KES 10,000" with the body "It started with a simple rule: every time I received money, I saved ten per cent first." Set status to Published and the published date to 10 November 2026.
- Add "Five free places to study in Nairobi" with the body "Libraries, quiet cafés and university spaces where you can revise without spending a shilling." Publish it with the date 14 November 2026.
- Add a third post, "My matatu diary", and leave it as Draft.
- Open
http://127.0.0.1:8000/.
The home page shows the two published posts, newest first. The draft is hidden, and there's no pagination bar because everything fits on one page:
Click the first post and submit a comment with the name "Otieno" and the text "Thanks! The library tip is gold." The page reloads (Post/Redirect/Get) with a success message, and the comments section now begins:
The comment's date and time will match when you post it.
Finally, try http://127.0.0.1:8000/my-matatu-diary/: you get a 404, because drafts aren't public.
Getting a 404 for a post you just wrote, or not seeing it on the home page. Check that its status is Published and that the slug in the address matches the one saved in the admin. If you later add a filter such as published_at__lte=timezone.now(), posts dated in the future will be hidden too.
Extend it
- Tags: add a
Tagmodel with aManyToManyFieldonPost, and a page at/tag/<slug>/listing posts with that tag. - Search: add a search box that filters posts with
Q(title__icontains=q) | Q(body__icontains=q)(see ORM Queries). - Writers without the admin: let logged-in users with the
blog.add_postpermission write and edit their own posts usingCreateView,UpdateView,PermissionRequiredMixinandUserPassesTestMixin(see Permissions), then deploy it for your friends to read.
Key points
- Models with
TextChoices, a uniqueSlugFieldand aForeignKeygive you drafts, readable URLs and authors. - The admin, with
prepopulated_fieldsand inlines, makes a ready-made writing dashboard. ListViewwithpaginate_byand a function view with aModelFormcover listing and commenting.- Template inheritance, static files and the messages framework tie the pages together into one site.
Tip: use the ← and → keys to move between pages.
