Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 77 ยท Middleware, Signals and Internals

Useful contrib Apps: humanize, flatpages, redirects

Use three small Django contrib apps: humanize for friendly numbers and dates, flatpages for editor-managed static pages, and redirects for moved URLs, each with a live example.

Django ships a set of optional packages under django.contrib. You already use some of them without thinking about it: auth, sessions, admin, staticfiles. Others solve small, specific problems that come up on almost every real site. This lesson covers three of them, each of which saves you from writing a model, a view and a template that Django has already written:

App Solves
django.contrib.humanize Showing numbers and dates the way people say them: "1.2 billion", "5 minutes ago", "22nd"
django.contrib.flatpages Pages such as About, Terms and Privacy that editors maintain in the admin, without touching code
django.contrib.redirects Sending old URLs to new ones after you rename or move pages, so links and search rankings survive

(You met sitemaps and syndication in Sitemaps, RSS Feeds and robots.txt, and sites, which flatpages and redirects both use to know which website a row belongs to.)

To enable any contrib app you add it to INSTALLED_APPS; those with models also need migrate. The example in this lesson turns all three on in one project and exercises them.

humanize: friendlier numbers and dates

humanize is a template tag library. Add "django.contrib.humanize" to INSTALLED_APPS and write {% load humanize %} in the template. It adds filters that turn machine-precise values into human wording:

Filter Example input Output
intcomma 1234567 1,234,567
intword 1200000000 1.2 billion
apnumber 7 (and 12) seven (and 12: only 1 to 9 are spelled out, following newspaper style)
ordinal 22 22nd
naturalday today's date today (also yesterday, tomorrow; other dates use the normal format)
naturaltime five minutes ago 5 minutes ago (and in 3 hours for the future)

These respect the active language, so they follow the rules in Internationalization and Localization in Depth, and intcomma uses the locale's thousand separator when localization is on.

flatpages: pages editors can change

Most sites have a few static pages that rarely change. Writing a view, URL and template for each one is overkill, but hard-coding the text means every typo fix needs a developer and a deploy. A FlatPage is a database row with a url, a title and HTML content, editable in the admin.

Setup has three parts:

  1. Add django.contrib.sites and django.contrib.flatpages to INSTALLED_APPS, set SITE_ID = 1, and run migrate.
  2. Create a template named flatpages/default.html. It receives a flatpage variable with title and content. Extend your base layout there so the page matches the site.
  3. Route requests to flatpages. The simplest way is FlatpageFallbackMiddleware: if a request would be a 404, the middleware checks whether a flat page exists at that URL. A request that matches a real URL pattern is never touched.
Python
# settings.py (read-only)
MIDDLEWARE = [
    # ...
    "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware",   # keep it last
]

The alternative is an explicit path("pages/", include("django.contrib.flatpages.urls")), which gives all flat pages a prefix and is easier to reason about on a large site. Flat pages can also require login (registration_required) or use a custom template (template_name).

Two cautions. First, content is trusted HTML and is rendered without escaping, so only editors you trust should have the permission to change flat pages (see Permissions, Groups and Authorization). Second, a fallback that fires on 404s means every missing URL costs one extra database query, which is cheap but worth knowing. Because flatpages have get_absolute_url(), they can be included in a Sitemap subclass (FlatPageSitemap ships in the app).

redirects: keeping old URLs alive

When you rename /old-blog/ to /blog/, every link on other sites and every search result for the old address breaks, and visitors see a 404. A redirect answers the old URL with a 301 Moved Permanently pointing to the new one, so browsers, bookmarks and search engines follow along.

django.contrib.redirects stores Redirect rows (site, old_path, new_path). RedirectFallbackMiddleware works like the flatpages one: when a request would end in a 404, it looks up the path in the table. A row with an empty new_path answers 410 Gone, which tells search engines the page was removed on purpose.

Python
# settings.py (read-only)
INSTALLED_APPS += ["django.contrib.sites", "django.contrib.redirects"]
SITE_ID = 1
MIDDLEWARE += ["django.contrib.redirects.middleware.RedirectFallbackMiddleware"]

Redirects are managed in the admin, so a content editor can fix a broken link without a deploy. For a handful of fixed redirects known at development time, you can also write them in code with RedirectView (path("old-blog/", RedirectView.as_view(url="/blog/", permanent=True))), which needs no database. Use the table when editors, not developers, own the list.

All three, running

Python humanize, flatpages and redirects together

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.

Notice how little code the three features needed: only settings, two database rows and one template. The flat page was served even though urlpatterns is empty, because the middleware caught the 404. /about (no slash) was redirected to /about/ by the flatpages middleware itself, which honors APPEND_SLASH. The humanize lines show that 11 becomes 11th (not 11st: the filter knows the exceptions), 12 stays a digit because only 1 to 9 are written as words, and a time two and a half hours in the future reads 2 hours from now.

When to use something else

  • Flatpages fit a handful of simple pages. If editors need images, layouts, drafts or a page tree, use a CMS package (such as Wagtail) or build your own model.
  • A redirect table suits editor-managed lists. For large-scale URL changes (thousands of rules), put the mapping in your web server or CDN so Django is not involved at all.
  • humanize is for display only. Do not use naturaltime text in APIs; send ISO timestamps and let the client format them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does FlatpageFallbackMiddleware decide when to look for a flat page?

    The middleware runs after the view. If the response is a 404, it checks for a FlatPage with that URL, so real URL patterns always win.
  2. 2. What status does RedirectFallbackMiddleware send when a Redirect row has an empty new_path?

    An empty new_path means the page was intentionally removed, so Django answers 410 Gone. A filled new_path gives a 301.
  3. 3. Which filter turns 1200000000 into '1.2 billion'?

    intword spells out the magnitude of large numbers. intcomma only adds thousands separators.
  4. 4. Why should only trusted users be allowed to edit flat pages?

    FlatPage.content is trusted HTML. Limit the change permission to staff you trust, or sanitize the content.

Summary

  • Contrib apps are optional packages you enable in INSTALLED_APPS; the three here each replace a small amount of repetitive code.
  • humanize ({% load humanize %}) provides intcomma, intword, apnumber, ordinal, naturalday and naturaltime for display.
  • flatpages stores editable pages in the database, rendered with flatpages/default.html and found by a 404-fallback middleware or an explicit URL include.
  • redirects keeps old URLs working with 301 responses (or 410 for removed pages) from rows editors manage in the admin.
  • Both middleware-based apps need django.contrib.sites and only run when no real URL matched.

Next: Deploying Django.