flatpages.txt 12 KB

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