The flatpages app

Django comes with an optional "flatpages" application. It lets you store simple"flat" HTML content in a database and handles the management for you viaDjango's admin interface and a Python API.

A flatpage is a simple object with a URL, title and content. Use it forone-off, special-case pages, such as "About" or "Privacy Policy" pages, thatyou want to store in a database but for which you don't want to develop acustom Django application.

A flatpage can use a custom template or a default, systemwide flatpagetemplate. It can be associated with one, or multiple, sites.

The content field may optionally be left blank if you prefer to put yourcontent in a custom template.

Here are some examples of flatpages on Django-powered sites:

Installation

To install the flatpages app, follow these steps:

Also make sure you've correctly set SITE_ID to the ID of thesite the settings file represents. This will usually be 1 (i.e.SITE_ID = 1, but if you're using the sites framework to managemultiple sites, it could be the ID of a different site.

Then either:

  • Add an entry in your URLconf. For example:
  1. urlpatterns = [
  2. path('pages/', include('django.contrib.flatpages.urls')),
  3. ]

or:

How it works

manage.py migrate creates two tables in your database: django_flatpageand django_flatpage_sites. django_flatpage is a simple lookup tablethat simply maps a URL to a title and bunch of text content.django_flatpage_sites associates a flatpage with a site.

Using the URLconf

There are several ways to include the flat pages in your URLconf. You candedicate a particular path to flat pages:

  1. urlpatterns = [
  2. path('pages/', include('django.contrib.flatpages.urls')),
  3. ]

You can also set it up as a "catchall" pattern. In this case, it is importantto place the pattern at the end of the other urlpatterns:

  1. from django.contrib.flatpages import views
  2.  
  3. # Your other patterns here
  4. urlpatterns += [
  5. path('<path:url>', views.flatpage),
  6. ]

警告

If you set APPEND_SLASH to False, you must remove the slashin the catchall pattern or flatpages without a trailing slash will not bematched.

Another common setup is to use flat pages for a limited set of known pages andto hard code the urls, so you can reference them with the url templatetag:

  1. from django.contrib.flatpages import views
  2.  
  3. urlpatterns += [
  4. path('about-us/', views.flatpage, {'url': '/about-us/'}, name='about'),
  5. path('license/', views.flatpage, {'url': '/license/'}, name='license'),
  6. ]

Using the middleware

The FlatpageFallbackMiddlewarecan do all of the work.

  • class FlatpageFallbackMiddleware
  • Each time any Django application raises a 404 error, this middlewarechecks the flatpages database for the requested URL as a last resort.Specifically, it checks for a flatpage with the given URL with a site IDthat corresponds to the SITE_ID setting.

If it finds a match, it follows this algorithm:

  • If the flatpage has a custom template, it loads that template.Otherwise, it loads the template flatpages/default.html.
  • It passes that template a single context variable, flatpage,which is the flatpage object. It usesRequestContext in rendering thetemplate.
    The middleware will only add a trailing slash and redirect (by lookingat the APPEND_SLASH setting) if the resulting URL refers toa valid flatpage. Redirects are permanent (301 status code).

If it doesn't find a match, the request continues to be processed as usual.

The middleware only gets activated for 404s — not for 500s or responsesof any other status code.

Flatpages will not apply view middleware

Because the FlatpageFallbackMiddleware is applied only afterURL resolution has failed and produced a 404, the response itreturns will not apply any view middlewaremethods. Only requests which are successfully routed to a view vianormal URL resolution apply view middleware.

Note that the order of MIDDLEWARE matters. Generally, you can putFlatpageFallbackMiddleware at theend of the list. This means it will run first when processing the response, andensures that any other response-processing middleware see the real flatpageresponse rather than the 404.

For more on middleware, read the middleware docs.

Ensure that your 404 template works

Note that theFlatpageFallbackMiddlewareonly steps in once another view has successfully produced a 404 response.If another view or middleware class attempts to produce a 404 but ends upraising an exception instead, the response will become an HTTP 500("Internal Server Error") and theFlatpageFallbackMiddlewarewill not attempt to serve a flat page.

How to add, change and delete flatpages

Via the admin interface

If you've activated the automatic Django admin interface, you should see a"Flatpages" section on the admin index page. Edit flatpages as you edit anyother object in the system.

The FlatPage model has an enable_comments field that isn't used bycontrib.flatpages, but that could be useful for your project or third-partyapps. It doesn't appear in the admin interface, but you can add it byregistering a custom ModelAdmin for FlatPage:

  1. from django.contrib import admin
  2. from django.contrib.flatpages.admin import FlatPageAdmin
  3. from django.contrib.flatpages.models import FlatPage
  4. from django.utils.translation import gettext_lazy as _
  5.  
  6. # Define a new FlatPageAdmin
  7. class FlatPageAdmin(FlatPageAdmin):
  8. fieldsets = (
  9. (None, {'fields': ('url', 'title', 'content', 'sites')}),
  10. (_('Advanced options'), {
  11. 'classes': ('collapse',),
  12. 'fields': (
  13. 'enable_comments',
  14. 'registration_required',
  15. 'template_name',
  16. ),
  17. }),
  18. )
  19.  
  20. # Re-register FlatPageAdmin
  21. admin.site.unregister(FlatPage)
  22. admin.site.register(FlatPage, FlatPageAdmin)

Via the Python API

Check for duplicate flatpage URLs.

If you add or modify flatpages via your own code, you will likely want tocheck for duplicate flatpage URLs within the same site. The flatpage formused in the admin performs this validation check, and can be imported fromdjango.contrib.flatpages.forms.FlatpageForm and used in your ownviews.

Flatpage templates

By default, flatpages are rendered via the templateflatpages/default.html, but you can override that for aparticular flatpage: in the admin, a collapsed fieldset titled"Advanced options" (clicking will expand it) contains a field forspecifying a template name. If you're creating a flat page via thePython API you can simply set the template name as the fieldtemplate_name on the FlatPage object.

Creating the flatpages/default.html template is your responsibility;in your template directory, just create a flatpages directorycontaining a file default.html.

Flatpage templates are passed a single context variable, flatpage,which is the flatpage object.

Here's a sample flatpages/default.html template:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>{{ flatpage.title }}</title>
  5. </head>
  6. <body>
  7. {{ flatpage.content }}
  8. </body>
  9. </html>

Since you're already entering raw HTML into the admin page for a flatpage,both flatpage.title and flatpage.content are marked as notrequiring automatic HTML escaping in thetemplate.

Getting a list of FlatPage objects in your templates

The flatpages app provides a template tag that allows you to iterateover all of the available flatpages on the current site.

Like all custom template tags, you'll need to load its customtag library before you can useit. After loading the library, you can retrieve all current flatpagesvia the get_flatpages tag:

  1. {% load flatpages %}
  2. {% get_flatpages as flatpages %}
  3. <ul>
  4. {% for page in flatpages %}
  5. <li><a href="{{ page.url }}">{{ page.title }}</a></li>
  6. {% endfor %}
  7. </ul>

Displaying registration_required flatpages

By default, the get_flatpages template tag will only showflatpages that are marked registration_required = False. If youwant to display registration-protected flatpages, you need to specifyan authenticated user using a for clause.

For example:

  1. {% get_flatpages for someuser as about_pages %}

If you provide an anonymous user, get_flatpages will behavethe same as if you hadn't provided a user — i.e., it will only show youpublic flatpages.

Limiting flatpages by base URL

An optional argument, starts_with, can be applied to limit thereturned pages to those beginning with a particular base URL. Thisargument may be passed as a string, or as a variable to be resolvedfrom the context.

For example:

  1. {% get_flatpages '/about/' as about_pages %}
  2. {% get_flatpages about_prefix as about_pages %}
  3. {% get_flatpages '/about/' for someuser as about_pages %}

Integrating with django.contrib.sitemaps

Example

Here's an example of a URLconf using FlatPageSitemap:

  1. from django.contrib.flatpages.sitemaps import FlatPageSitemap
  2. from django.contrib.sitemaps.views import sitemap
  3. from django.urls import path
  4.  
  5. urlpatterns = [
  6. # ...
  7.  
  8. # the sitemap
  9. path('sitemap.xml', sitemap,
  10. {'sitemaps': {'flatpages': FlatPageSitemap}},
  11. name='django.contrib.sitemaps.views.sitemap'),
  12. ]