Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Project: A Blog API with JWT, Comments and Moderation

Build a blog API with Django REST Framework: JWT login, draft and published posts, author-only editing, comments that need moderator approval, throttled posting and a tested permission model.

A blog sounds easy until you list the rules. Visitors read published posts, but authors also see their own drafts. Only an author edits their post. Readers may comment, but a comment stays hidden until a moderator approves it, and nobody should be able to flood a post with comments. This is an excellent project for practicing a layered permission model, because the rules differ per role, per object and per state.

You will use JWT for authentication (JWT lesson), custom permission classes (permission lessons), a queryset that depends on who is asking, actions for state changes, and a throttle on comments.

The rule book

Who may do what

Visitor Reads published posts and approved comments
Author Writes, edits, publishes own posts; sees own drafts
Moderator Approves or removes any comment
Reader Posts comments, which wait for approval

A rule you cannot state in one sentence cannot be tested

1 / 2

Write each rule as a sentence, then as a test. The code below is the translation.

Rule Where it lives
Visitors see only published posts get_queryset()
Authors also see their own drafts get_queryset() with Q
Only the author edits or deletes a post IsAuthorOrReadOnly (object permission)
publish is an author action @action + the same permission
Anyone signed in may comment; comments start unapproved perform_create
Visitors see only approved comments queryset
Moderators approve comments IsModerator permission on one action

Part 1: posts, drafts and JWT login

Moderators are a Django group, which is the standard way to model a role. Checking user.groups.filter(name="moderators") on every request costs a query, so the permission below fetches it only when it is needed.

Python Part 1: JWT login, drafts and author-only editing

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.

Output:

TEXT
ann creates: 1 published = False
anonymous sees: [] | ann sees: ['Hello DRF'] | bob sees: []
bob opens ann's draft -> 404
anonymous tries to post -> 401
ann publishes -> True
anonymous sees: ['Hello DRF'] | bob sees: ['Hello DRF']
bob edits ann's post -> 403
bob publishes it -> 403
ann edits her post -> Hello, DRF

Look at what each rule used. Visibility is in the queryset, so a stranger gets 404 for a draft. Editing is an object permission, so Bob gets 403 for a post he can see but does not own. Both mechanisms are needed, and they answer different questions: "does this exist for you?" and "may you change it?".

Part 2: comments, moderation and throttling

Comments follow the same pattern with one extra concept, a moderation state. Unapproved comments are visible only to their author and to moderators. Because posting is cheap and attractive to spammers, the create action gets a scoped throttle.

Python Part 2: approval queue, moderator permission, throttle

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.

Output:

TEXT
anonymous comments -> 403
ann comments -> 201 approved = False
anonymous sees: []
ann sees her own pending comment: ['Great post!']
ann tries to approve -> 403 {'detail': 'Only moderators can do this.'}
moderator approves -> True
anonymous sees: ['Great post!']
next three comments from ann -> [201, 201, 429]
a minute later -> 201
moderator deletes #1 -> 204

Several details deserve attention:

  • get_permissions() returns different permission objects per action: the default for reading and creating, IsModerator for approve and destroy.
  • The moderator check calls the database for group membership. In a busy API, cache it on the request or put a boolean is_moderator into the JWT claims (and accept that role changes take effect when the token is refreshed).
  • The comment queryset is filtered by post_pk from the URL, so a comment can never be reached through the wrong post. Nested routing libraries (drf-nested-routers) automate this; the explicit version shows what happens underneath.
  • Throttling counts creations only, because get_throttles() returns the throttle for the create action and nothing for reads. If reads need protection too, give them their own scope.

Part 3: tests that guard the rules

Turn every sentence of the rule book into a test; this is where the permission matrix from Testing Auth and Permissions pays off. A starter list:

  1. An anonymous visitor cannot see a draft (404), and sees it after publishing (200).
  2. A stranger gets 403 when editing or publishing someone else's visible post.
  3. A comment starts unapproved, is hidden from the public, visible to its author and to moderators.
  4. A normal user gets 403 from the approve action; a moderator gets 200.
  5. The fourth comment inside a minute gets 429; it works after the window.
  6. The post list does not issue a query per post (assertNumQueries).

Extension ideas

  • Comment replies (a parent foreign key) and a ?post= filter.
  • Slugs as public identifiers with lookup_field = "slug" instead of numeric IDs, which also prevents ID guessing.
  • Tags, search and ordering by popularity (search and ordering).
  • Image upload for a post cover with ImageField, MultiPartParser and size limits.
  • JWT refresh and logout (blacklist) so a stolen refresh token can be revoked.
  • An RSS or Atom feed with a custom renderer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Bob can see a published post by Ann but gets 403 when he edits it. Which mechanism produced the 403?

    The post exists for Bob (queryset allows it), but the object permission refuses the write.
  2. 2. Why does a draft by Ann return 404 for Bob rather than 403?

    Filtering the queryset by visibility removes the object entirely, which also avoids revealing that it exists.
  3. 3. How can one ViewSet apply a stricter permission to only some actions?

    get_permissions() can return different permission instances per action.
  4. 4. Where should the author of a new post or comment come from?

    Identity must come from authentication, not from client-supplied data.

Summary

  • Write the role rules as sentences, map each to a mechanism, and then to a test.
  • Use the queryset for visibility (drafts, pending comments), object permissions for who may change something, and actions for state changes such as publish and approve.
  • get_permissions() lets one viewset apply different rules per action; groups model roles such as moderators.
  • Scope a throttle to the abuse-prone action, set authors from request.user, and keep nested objects tied to their parent through the URL.

Next: Practice: DRF Exercises and Interview Questions