The Four Views

Almost every application is these four things repeated. Once you have written them once, properly, most features are a variation.

Read is a list and a detail. Create is a form that saves. Update is the same form bound to an existing object. Delete needs a confirmation step and must be a POST.

Delete must never be a GET. A link that deletes is a trap: browsers prefetch links, crawlers follow them, and someone's accelerator extension will eventually visit every link on a page including that one.

The correct shape is a confirmation page, then a form that POSTs. It is slightly more work and it is the difference between a delete button and a mine.

Update reuses everything. The same form class, bound to the instance with PostForm(request.POST, instance=post). That is the whole difference between creating and editing, which is why the two views look almost identical and are often merged.

◈ Graded Challenge

Write unique_slug(title, taken) producing a URL-safe slug that does not collide. Lowercase the title, replace every run of characters that are not letters or digits with a single hyphen, and strip hyphens from both ends. If the result is not in taken, return it. If it is, append -2, and if that is taken too try -3, and so on until one is free.

Name it exactly: unique_slug(title, taken)

Python4 visible + 4 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Messages and Pagination →
← Back