Django Capstone: A Blog
The blog is the capstone app. It lists posts, shows one post, and takes new ones.
Make the model
The Post model holds a title and a body. The table holds one row per post.
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"Make the form
The form is a ModelForm for the Post model. It holds the title and the body fields.
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "body"]List the posts
The view reads the posts in title order. The template loops over them.
def post_list(request):
posts = Post.objects.all().order_by("title")
template = Template("{% for post in posts %}<h2>{{ post.title }}</h2><p>{{ post.body }}</p>{% endfor %}")
return HttpResponse(template.render(Context({"posts": posts})))Show one post
The view fetches one post by its number. A missing number sends a 404.
def post_detail(request, post_id):
post = get_object_or_404(Post, pk=post_id)
template = Template("<h1>{{ post.title }}</h1><p>{{ post.body }}</p>")
return HttpResponse(template.render(Context({"post": post})))Add a post
A POST checks the form and saves it. A GET shows the empty form.
def add_post(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
form.save()
return post_list(request)
else:
form = PostForm()
template = Template('<h1>Add a post</h1><form method="post">{{ form }}</form>')
return HttpResponse(template.render(Context({"form": form})))The form fields
The form holds two fields, title and body. This print shows their names.
print(list(PostForm().fields))Add two posts, then read the blog
The test client adds two posts through the form. The prints show the finished list, the first post, and the count.
client = Client()
client.post("/add/", data={"title": "First post", "body": "Hello from Django."})
client.post("/add/", data={"title": "Second post", "body": "Models save rows."})
print(client.get("/").content.decode())
print(client.get("/post/1/").content.decode())
print(Post.objects.count())Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django import forms
from django.db import connection, models
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.template import Context, Template
from django.urls import path
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"
with connection.schema_editor() as editor:
editor.create_model(Post)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "body"]
def post_list(request):
posts = Post.objects.all().order_by("title")
template = Template("{% for post in posts %}<h2>{{ post.title }}</h2><p>{{ post.body }}</p>{% endfor %}")
return HttpResponse(template.render(Context({"posts": posts})))
def post_detail(request, post_id):
post = get_object_or_404(Post, pk=post_id)
template = Template("<h1>{{ post.title }}</h1><p>{{ post.body }}</p>")
return HttpResponse(template.render(Context({"post": post})))
def add_post(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
form.save()
return post_list(request)
else:
form = PostForm()
template = Template('<h1>Add a post</h1><form method="post">{{ form }}</form>')
return HttpResponse(template.render(Context({"form": form})))
urlpatterns = [path("", post_list), path("post/<int:post_id>/", post_detail), path("add/", add_post)]
from django.test import Client
client = Client()
client.post("/add/", data={"title": "First post", "body": "Hello from Django."})
client.post("/add/", data={"title": "Second post", "body": "Models save rows."})
print(client.get("/").content.decode())
print(client.get("/post/1/").content.decode())
print(Post.objects.count())
Key points
- GET / lists the posts in title order.
- GET /post/1/ shows the first post.
- POST /add/ saves a post through the form.
- The form is a ModelForm for the Post model.
- The posts live in the database.
In this example, the setup lines configure Django. The program creates the table directly. A real project uses migrations for this step. The Post model holds a title and a body. The PostForm is a ModelForm for the Post model. The list view reads the posts in title order and renders them with a loop. The detail view fetches one post by its number. The add view checks the form on a POST and saves it. A real project adds the CSRF token to the form. The test client adds two posts through the form. The prints show the finished list, the first post, and the count of two.
Note
The list view orders by title, so the order stays fixed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens after POST /add/ saves a post?