Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 77 ยท Projects

Project: Blog

Build a complete Django blog: posts with unique slugs, moderated comments, generic views, templates, the admin site and tests, running live in your browser.

A blog is the classic first real Django project because it touches nearly everything you have learned: models and relationships, generic views, templates, forms, the admin and tests. It is also small enough to understand completely.

In this project you will build a blog where an author writes posts in the admin, visitors read published posts, and readers leave comments that appear only after a moderator approves them. You will work in two steps: first the data layer and the admin, then the public pages and a test suite. Both run live in your browser in one Python process, so there is no manage.py and no files, but the code is the same code you would put in a real project.

The plan

Before writing code, decide what the site must do:

  • Posts have a title, a unique slug for the URL, a body, an author and a status (draft or published). Visitors must never see drafts.
  • Comments belong to a post and have a name, text and an approved flag that starts as False.
  • Public pages: a paginated list of posts and a detail page with the comments and a comment form.
  • Admin: write and edit posts, see comments inside each post, and approve many comments with one action.
  • Tests that prove the rules above, especially the ones about drafts and moderation.
erDiagram
    USER ||--o{ POST : writes
    POST ||--o{ COMMENT : has
    POST {
        string title
        string slug
        text body
        string status
        datetime created
    }
    COMMENT {
        string name
        text body
        bool approved
    }

Each post has one author and many comments. The approved flag on a comment is what moderation changes.

In a real project this would be an app created with python manage.py startapp blog, with the code split into models.py, views.py, forms.py, admin.py, urls.py and tests.py. In the live examples everything shares one script, but the sections are labelled so you can see where each piece would live.

Step 1: models and the admin

Three details in the models are worth studying.

A manager for published posts. Post.published returns only published posts. Views use it, so a draft can never leak by accident, which is better than remembering to filter in every view. (See custom managers.)

A unique slug. The URL /posts/my-first-post/ is friendlier than /posts/17/. The slug is created from the title in save(), and a number is added if it already exists.

Moderated comments. approved defaults to False, so nothing a stranger writes is shown until you say so.

The admin part registers both models. PostAdmin pre-fills the slug while you type the title, shows comments inline, and filters by status. CommentAdmin has an action that approves the selected comments. The script then logs in as a superuser through the test client and uses the admin exactly as a person would.

Python Blog models, manager, slugs and admin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The admin pages returned 200, the inline form listed the comment, and posting the approve_comments action changed exactly one row. Notice that the two posts titled "Hello World!" got the slugs hello-world and hello-world-2, and that only one of three posts is visible through Post.published.

In a real project, running python manage.py makemigrations blog and migrate creates the tables instead of schema_editor, and python manage.py createsuperuser makes the account. The admin lessons cover every option used above.

Step 2: public pages, comments and tests

Now the visitor's side. The views are class-based generic views from Generic Display and Editing Views:

  • PostListView is a ListView over Post.published, with paginate_by = 2 so you can see paging with few posts.
  • PostDetailView is a DetailView mixed with FormMixin. A GET shows the post, its approved comments and an empty form. A POST validates the form, saves a new unapproved comment and redirects back to the post. Redirecting after a successful POST stops a page refresh from submitting the form again (the post/redirect/get pattern from Handling Forms in Views).
  • A CommentForm is a ModelForm with only name and body. The post itself is attached in the view, never taken from the form, so a visitor cannot attach a comment to a different post by editing the HTML.

The templates use inheritance: a base.html with a content block, extended by the list and detail pages. They are stored in a dictionary and loaded with the locmem loader, which stands in for the templates/ folder of a real project.

One more point about security: the template prints {{ comment.body }} with automatic escaping, so a comment containing <script> is displayed as harmless text. The test suite checks this, because "user input is escaped" is exactly the kind of rule a test should protect.

The tests at the end use Django's TestCase, which wraps each test in a transaction that is rolled back, so tests never leak data into each other. Normally you run them with python manage.py test. Here a small script runs the same classes through the standard unittest runner, and prints one line per test.

Python Views, templates, comment form and tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every test passed. The comment test is the most valuable one: it proves that a new comment is invisible, then visible after approval, in four lines. If someone later breaks moderation, this test fails the same day.

Two notes on the tests. First, setUpTestData runs once per class and its objects are shared safely; it is faster than creating them in every test. Second, the self.client object is a fresh test client for every test, with no cookies left over. More patterns are in Testing Django Apps.

Where to take it next

A working blog is a good base for extension exercises, each of which uses something from this tutorial:

  • Add tags with a ManyToManyField and a page listing posts per tag (relationships).
  • Add an RSS feed with django.contrib.syndication.
  • Add search with title__icontains, and later PostgreSQL full-text search.
  • Let logged-in users comment without typing a name (authentication).
  • Cache the post list and invalidate it when a post is saved (caching).
  • Count page views with an F() expression, as in the URL shortener project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project use a custom manager (Post.published) instead of filtering in each view?

    Putting the rule in one place means every view that uses the manager follows it. Repeating the filter in every view invites a mistake that exposes drafts.
  2. 2. Why is the comment's post set in the view with commit=False rather than included in the form?

    Values the user must not control belong on the server side. save(commit=False) returns an unsaved object so the view can set the post before saving.
  3. 3. What does the redirect after a successful comment POST prevent?

    After a redirect, the browser's current page is a GET request, so refreshing repeats the GET instead of sending the comment again.
  4. 4. How does the blog make sure a comment containing <script> tags is not executed?

    {{ comment.body }} converts < and > to entities. The test test_comment_html_is_escaped guards this behavior.
  5. 5. What is the benefit of Django's TestCase wrapping each test in a transaction?

    Rolling back after each test gives every test a clean database without the cost of recreating tables.

Summary

  • Start a project by writing down the rules: who sees what, and what needs approval. Then turn the important rules into tests.
  • A custom manager such as Post.published keeps visibility rules in one place.
  • Generate slugs in save() and make them unique, so URLs stay readable.
  • Moderation is a boolean that defaults to False; the admin action approve_comments flips it for many rows at once.
  • DetailView plus FormMixin handles a page that shows an object and also accepts a form; use commit=False to set server-controlled fields.
  • Redirect after a successful POST, and let template autoescaping protect against injected HTML.
  • TestCase with setUpTestData gives fast, isolated tests that read like a specification.

Next lesson: Project: Todo JSON API.