1. =================
    
  2. The flatpages app
    
  3. =================
    
  4. 
    
  5. .. module:: django.contrib.flatpages
    
  6.    :synopsis: A framework for managing simple ?flat? HTML content in a database.
    
  7. 
    
  8. Django comes with an optional "flatpages" application. It lets you store "flat"
    
  9. HTML content in a database and handles the management for you via Django's
    
  10. admin interface and a Python API.
    
  11. 
    
  12. A flatpage is an object with a URL, title and content. Use it for one-off,
    
  13. special-case pages, such as "About" or "Privacy Policy" pages, that you want to
    
  14. store in a database but for which you don't want to develop a custom Django
    
  15. application.
    
  16. 
    
  17. A flatpage can use a custom template or a default, systemwide flatpage
    
  18. template. It can be associated with one, or multiple, sites.
    
  19. 
    
  20. The content field may optionally be left blank if you prefer to put your
    
  21. content in a custom template.
    
  22. 
    
  23. Installation
    
  24. ============
    
  25. 
    
  26. To install the flatpages app, follow these steps:
    
  27. 
    
  28. 1. Install the :mod:`sites framework <django.contrib.sites>` by adding
    
  29.    ``'django.contrib.sites'`` to your :setting:`INSTALLED_APPS` setting,
    
  30.    if it's not already in there.
    
  31. 
    
  32.    Also make sure you've correctly set :setting:`SITE_ID` to the ID of the
    
  33.    site the settings file represents. This will usually be ``1`` (i.e.
    
  34.    ``SITE_ID = 1``, but if you're using the sites framework to manage
    
  35.    multiple sites, it could be the ID of a different site.
    
  36. 
    
  37. 2. Add ``'django.contrib.flatpages'`` to your :setting:`INSTALLED_APPS`
    
  38.    setting.
    
  39. 
    
  40. Then either:
    
  41. 
    
  42. 3. Add an entry in your URLconf. For example::
    
  43. 
    
  44.     urlpatterns = [
    
  45.         path('pages/', include('django.contrib.flatpages.urls')),
    
  46.     ]
    
  47. 
    
  48. or:
    
  49. 
    
  50. 3. Add ``'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'``
    
  51.    to your :setting:`MIDDLEWARE` setting.
    
  52. 
    
  53. 4. Run the command :djadmin:`manage.py migrate <migrate>`.
    
  54. 
    
  55. .. currentmodule:: django.contrib.flatpages.middleware
    
  56. 
    
  57. How it works
    
  58. ============
    
  59. 
    
  60. ``manage.py migrate`` creates two tables in your database: ``django_flatpage``
    
  61. and ``django_flatpage_sites``. ``django_flatpage`` is a lookup table that maps
    
  62. a URL to a title and bunch of text content. ``django_flatpage_sites``
    
  63. associates a flatpage with a site.
    
  64. 
    
  65. Using the URLconf
    
  66. -----------------
    
  67. 
    
  68. There are several ways to include the flat pages in your URLconf. You can
    
  69. dedicate a particular path to flat pages::
    
  70. 
    
  71.     urlpatterns = [
    
  72.         path('pages/', include('django.contrib.flatpages.urls')),
    
  73.     ]
    
  74. 
    
  75. You can also set it up as a "catchall" pattern. In this case, it is important
    
  76. to place the pattern at the end of the other urlpatterns::
    
  77. 
    
  78.     from django.contrib.flatpages import views
    
  79. 
    
  80.     # Your other patterns here
    
  81.     urlpatterns += [
    
  82.         re_path(r'^(?P<url>.*/)$', views.flatpage),
    
  83.     ]
    
  84. 
    
  85. .. warning::
    
  86. 
    
  87.     If you set :setting:`APPEND_SLASH` to ``False``, you must remove the slash
    
  88.     in the catchall pattern or flatpages without a trailing slash will not be
    
  89.     matched.
    
  90. 
    
  91. Another common setup is to use flat pages for a limited set of known pages and
    
  92. to hard code the urls, so you can reference them with the :ttag:`url` template
    
  93. tag::
    
  94. 
    
  95.     from django.contrib.flatpages import views
    
  96. 
    
  97.     urlpatterns += [
    
  98.         path('about-us/', views.flatpage, {'url': '/about-us/'}, name='about'),
    
  99.         path('license/', views.flatpage, {'url': '/license/'}, name='license'),
    
  100.     ]
    
  101. 
    
  102. Using the middleware
    
  103. --------------------
    
  104. 
    
  105. The :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
    
  106. can do all of the work.
    
  107. 
    
  108. .. class:: FlatpageFallbackMiddleware
    
  109. 
    
  110.     Each time any Django application raises a 404 error, this middleware
    
  111.     checks the flatpages database for the requested URL as a last resort.
    
  112.     Specifically, it checks for a flatpage with the given URL with a site ID
    
  113.     that corresponds to the :setting:`SITE_ID` setting.
    
  114. 
    
  115.     If it finds a match, it follows this algorithm:
    
  116. 
    
  117.     * If the flatpage has a custom template, it loads that template.
    
  118.       Otherwise, it loads the template :file:`flatpages/default.html`.
    
  119. 
    
  120.     * It passes that template a single context variable, ``flatpage``,
    
  121.       which is the flatpage object. It uses
    
  122.       :class:`~django.template.RequestContext` in rendering the
    
  123.       template.
    
  124. 
    
  125.     The middleware will only add a trailing slash and redirect (by looking
    
  126.     at the :setting:`APPEND_SLASH` setting) if the resulting URL refers to
    
  127.     a valid flatpage. Redirects are permanent (301 status code).
    
  128. 
    
  129.     If it doesn't find a match, the request continues to be processed as usual.
    
  130. 
    
  131.     The middleware only gets activated for 404s -- not for 500s or responses
    
  132.     of any other status code.
    
  133. 
    
  134. .. admonition:: Flatpages will not apply view middleware
    
  135. 
    
  136.    Because the ``FlatpageFallbackMiddleware`` is applied only after
    
  137.    URL resolution has failed and produced a 404, the response it
    
  138.    returns will not apply any :ref:`view middleware <view-middleware>`
    
  139.    methods. Only requests which are successfully routed to a view via
    
  140.    normal URL resolution apply view middleware.
    
  141. 
    
  142. Note that the order of :setting:`MIDDLEWARE` matters. Generally, you can put
    
  143. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` at the
    
  144. end of the list. This means it will run first when processing the response, and
    
  145. ensures that any other response-processing middleware see the real flatpage
    
  146. response rather than the 404.
    
  147. 
    
  148. For more on middleware, read the :doc:`middleware docs
    
  149. </topics/http/middleware>`.
    
  150. 
    
  151. .. admonition:: Ensure that your 404 template works
    
  152. 
    
  153.     Note that the
    
  154.     :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
    
  155.     only steps in once another view has successfully produced a 404 response.
    
  156.     If another view or middleware class attempts to produce a 404 but ends up
    
  157.     raising an exception instead, the response will become an HTTP 500
    
  158.     ("Internal Server Error") and the
    
  159.     :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
    
  160.     will not attempt to serve a flat page.
    
  161. 
    
  162. .. currentmodule:: django.contrib.flatpages.models
    
  163. 
    
  164. How to add, change and delete flatpages
    
  165. =======================================
    
  166. 
    
  167. .. _flatpages-admin:
    
  168. 
    
  169. Via the admin interface
    
  170. -----------------------
    
  171. 
    
  172. If you've activated the automatic Django admin interface, you should see a
    
  173. "Flatpages" section on the admin index page. Edit flatpages as you edit any
    
  174. other object in the system.
    
  175. 
    
  176. The ``FlatPage`` model has an ``enable_comments`` field that isn't used by
    
  177. ``contrib.flatpages``, but that could be useful for your project or third-party
    
  178. apps. It doesn't appear in the admin interface, but you can add it by
    
  179. registering a custom ``ModelAdmin`` for ``FlatPage``::
    
  180. 
    
  181.     from django.contrib import admin
    
  182.     from django.contrib.flatpages.admin import FlatPageAdmin
    
  183.     from django.contrib.flatpages.models import FlatPage
    
  184.     from django.utils.translation import gettext_lazy as _
    
  185. 
    
  186.     # Define a new FlatPageAdmin
    
  187.     class FlatPageAdmin(FlatPageAdmin):
    
  188.         fieldsets = (
    
  189.             (None, {'fields': ('url', 'title', 'content', 'sites')}),
    
  190.             (_('Advanced options'), {
    
  191.                 'classes': ('collapse',),
    
  192.                 'fields': (
    
  193.                     'enable_comments',
    
  194.                     'registration_required',
    
  195.                     'template_name',
    
  196.                 ),
    
  197.             }),
    
  198.         )
    
  199. 
    
  200.     # Re-register FlatPageAdmin
    
  201.     admin.site.unregister(FlatPage)
    
  202.     admin.site.register(FlatPage, FlatPageAdmin)
    
  203. 
    
  204. Via the Python API
    
  205. ------------------
    
  206. 
    
  207. .. class:: FlatPage
    
  208. 
    
  209.     Flatpages are represented by a standard
    
  210.     :doc:`Django model </topics/db/models>`,
    
  211.     which lives in :source:`django/contrib/flatpages/models.py`. You can access
    
  212.     flatpage objects via the :doc:`Django database API </topics/db/queries>`.
    
  213. 
    
  214. .. currentmodule:: django.contrib.flatpages
    
  215. 
    
  216. .. admonition:: Check for duplicate flatpage URLs.
    
  217. 
    
  218.     If you add or modify flatpages via your own code, you will likely want to
    
  219.     check for duplicate flatpage URLs within the same site. The flatpage form
    
  220.     used in the admin performs this validation check, and can be imported from
    
  221.     ``django.contrib.flatpages.forms.FlatpageForm`` and used in your own
    
  222.     views.
    
  223. 
    
  224. Flatpage templates
    
  225. ==================
    
  226. 
    
  227. By default, flatpages are rendered via the template
    
  228. :file:`flatpages/default.html`, but you can override that for a
    
  229. particular flatpage: in the admin, a collapsed fieldset titled
    
  230. "Advanced options" (clicking will expand it) contains a field for
    
  231. specifying a template name. If you're creating a flat page via the
    
  232. Python API you can set the template name as the field ``template_name`` on the
    
  233. ``FlatPage`` object.
    
  234. 
    
  235. Creating the :file:`flatpages/default.html` template is your responsibility;
    
  236. in your template directory, create a :file:`flatpages` directory containing a
    
  237. file :file:`default.html`.
    
  238. 
    
  239. Flatpage templates are passed a single context variable, ``flatpage``,
    
  240. which is the flatpage object.
    
  241. 
    
  242. Here's a sample :file:`flatpages/default.html` template:
    
  243. 
    
  244. .. code-block:: html+django
    
  245. 
    
  246.     <!DOCTYPE html>
    
  247.     <html>
    
  248.     <head>
    
  249.     <title>{{ flatpage.title }}</title>
    
  250.     </head>
    
  251.     <body>
    
  252.     {{ flatpage.content }}
    
  253.     </body>
    
  254.     </html>
    
  255. 
    
  256. Since you're already entering raw HTML into the admin page for a flatpage,
    
  257. both ``flatpage.title`` and ``flatpage.content`` are marked as **not**
    
  258. requiring :ref:`automatic HTML escaping <automatic-html-escaping>` in the
    
  259. template.
    
  260. 
    
  261. Getting a list of :class:`~django.contrib.flatpages.models.FlatPage` objects in your templates
    
  262. ==============================================================================================
    
  263. 
    
  264. The flatpages app provides a template tag that allows you to iterate
    
  265. over all of the available flatpages on the :ref:`current site
    
  266. <hooking-into-current-site-from-views>`.
    
  267. 
    
  268. Like all custom template tags, you'll need to :ref:`load its custom
    
  269. tag library <loading-custom-template-libraries>` before you can use
    
  270. it. After loading the library, you can retrieve all current flatpages
    
  271. via the :ttag:`get_flatpages` tag:
    
  272. 
    
  273. .. code-block:: html+django
    
  274. 
    
  275.     {% load flatpages %}
    
  276.     {% get_flatpages as flatpages %}
    
  277.     <ul>
    
  278.         {% for page in flatpages %}
    
  279.             <li><a href="{{ page.url }}">{{ page.title }}</a></li>
    
  280.         {% endfor %}
    
  281.     </ul>
    
  282. 
    
  283. .. templatetag:: get_flatpages
    
  284. 
    
  285. Displaying ``registration_required`` flatpages
    
  286. ----------------------------------------------
    
  287. 
    
  288. By default, the :ttag:`get_flatpages` template tag will only show
    
  289. flatpages that are marked ``registration_required = False``. If you
    
  290. want to display registration-protected flatpages, you need to specify
    
  291. an authenticated user using a ``for`` clause.
    
  292. 
    
  293. For example:
    
  294. 
    
  295. .. code-block:: html+django
    
  296. 
    
  297.     {% get_flatpages for someuser as about_pages %}
    
  298. 
    
  299. If you provide an anonymous user, :ttag:`get_flatpages` will behave
    
  300. the same as if you hadn't provided a user -- i.e., it will only show you
    
  301. public flatpages.
    
  302. 
    
  303. Limiting flatpages by base URL
    
  304. ------------------------------
    
  305. 
    
  306. An optional argument, ``starts_with``, can be applied to limit the
    
  307. returned pages to those beginning with a particular base URL. This
    
  308. argument may be passed as a string, or as a variable to be resolved
    
  309. from the context.
    
  310. 
    
  311. For example:
    
  312. 
    
  313. .. code-block:: html+django
    
  314. 
    
  315.     {% get_flatpages '/about/' as about_pages %}
    
  316.     {% get_flatpages about_prefix as about_pages %}
    
  317.     {% get_flatpages '/about/' for someuser as about_pages %}
    
  318. 
    
  319. Integrating with :mod:`django.contrib.sitemaps`
    
  320. ===============================================
    
  321. 
    
  322. .. currentmodule:: django.contrib.flatpages.sitemaps
    
  323. 
    
  324. .. class:: FlatPageSitemap
    
  325. 
    
  326.     The :class:`sitemaps.FlatPageSitemap
    
  327.     <django.contrib.flatpages.sitemaps.FlatPageSitemap>` class looks at all
    
  328.     publicly visible :mod:`~django.contrib.flatpages` defined for the current
    
  329.     :setting:`SITE_ID` (see the :mod:`sites documentation
    
  330.     <django.contrib.sites>`) and creates an entry in the sitemap. These entries
    
  331.     include only the :attr:`~django.contrib.sitemaps.Sitemap.location`
    
  332.     attribute -- not :attr:`~django.contrib.sitemaps.Sitemap.lastmod`,
    
  333.     :attr:`~django.contrib.sitemaps.Sitemap.changefreq` or
    
  334.     :attr:`~django.contrib.sitemaps.Sitemap.priority`.
    
  335. 
    
  336. Example
    
  337. -------
    
  338. 
    
  339. Here's an example of a URLconf using :class:`FlatPageSitemap`::
    
  340. 
    
  341.     from django.contrib.flatpages.sitemaps import FlatPageSitemap
    
  342.     from django.contrib.sitemaps.views import sitemap
    
  343.     from django.urls import path
    
  344. 
    
  345.     urlpatterns = [
    
  346.         # ...
    
  347. 
    
  348.         # the sitemap
    
  349.         path('sitemap.xml', sitemap,
    
  350.             {'sitemaps': {'flatpages': FlatPageSitemap}},
    
  351.             name='django.contrib.sitemaps.views.sitemap'),
    
  352.     ]