flatpages.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 an 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. .. warning::
  119. Permissions to add or edit flatpages should be restricted to trusted users.
  120. Flatpages are defined by raw HTML and are **not sanitized** by Django. As a
  121. consequence, a malicious flatpage can lead to various security
  122. vulnerabilities, including permission escalation.
  123. .. _flatpages-admin:
  124. Via the admin interface
  125. -----------------------
  126. If you've activated the automatic Django admin interface, you should see a
  127. "Flatpages" section on the admin index page. Edit flatpages as you edit any
  128. other object in the system.
  129. The ``FlatPage`` model has an ``enable_comments`` field that isn't used by
  130. ``contrib.flatpages``, but that could be useful for your project or third-party
  131. apps. It doesn't appear in the admin interface, but you can add it by
  132. registering a custom ``ModelAdmin`` for ``FlatPage``::
  133. from django.contrib import admin
  134. from django.contrib.flatpages.admin import FlatPageAdmin
  135. from django.contrib.flatpages.models import FlatPage
  136. from django.utils.translation import gettext_lazy as _
  137. # Define a new FlatPageAdmin
  138. class FlatPageAdmin(FlatPageAdmin):
  139. fieldsets = [
  140. (None, {"fields": ["url", "title", "content", "sites"]}),
  141. (
  142. _("Advanced options"),
  143. {
  144. "classes": ["collapse"],
  145. "fields": [
  146. "enable_comments",
  147. "registration_required",
  148. "template_name",
  149. ],
  150. },
  151. ),
  152. ]
  153. # Re-register FlatPageAdmin
  154. admin.site.unregister(FlatPage)
  155. admin.site.register(FlatPage, FlatPageAdmin)
  156. Via the Python API
  157. ------------------
  158. .. class:: FlatPage
  159. Flatpages are represented by a standard
  160. :doc:`Django model </topics/db/models>`,
  161. which lives in :source:`django/contrib/flatpages/models.py`. You can access
  162. flatpage objects via the :doc:`Django database API </topics/db/queries>`.
  163. .. currentmodule:: django.contrib.flatpages
  164. .. admonition:: Check for duplicate flatpage URLs.
  165. If you add or modify flatpages via your own code, you will likely want to
  166. check for duplicate flatpage URLs within the same site. The flatpage form
  167. used in the admin performs this validation check, and can be imported from
  168. ``django.contrib.flatpages.forms.FlatpageForm`` and used in your own
  169. views.
  170. Flatpage templates
  171. ==================
  172. By default, flatpages are rendered via the template
  173. :file:`flatpages/default.html`, but you can override that for a
  174. particular flatpage: in the admin, a collapsed fieldset titled
  175. "Advanced options" (clicking will expand it) contains a field for
  176. specifying a template name. If you're creating a flat page via the
  177. Python API you can set the template name as the field ``template_name`` on the
  178. ``FlatPage`` object.
  179. Creating the :file:`flatpages/default.html` template is your responsibility;
  180. in your template directory, create a :file:`flatpages` directory containing a
  181. file :file:`default.html`.
  182. Flatpage templates are passed a single context variable, ``flatpage``,
  183. which is the flatpage object.
  184. Here's a sample :file:`flatpages/default.html` template:
  185. .. code-block:: html+django
  186. <!DOCTYPE html>
  187. <html>
  188. <head>
  189. <title>{{ flatpage.title }}</title>
  190. </head>
  191. <body>
  192. {{ flatpage.content }}
  193. </body>
  194. </html>
  195. Since you're already entering raw HTML into the admin page for a flatpage,
  196. both ``flatpage.title`` and ``flatpage.content`` are marked as **not**
  197. requiring :ref:`automatic HTML escaping <automatic-html-escaping>` in the
  198. template.
  199. Getting a list of :class:`~django.contrib.flatpages.models.FlatPage` objects in your templates
  200. ==============================================================================================
  201. The flatpages app provides a template tag that allows you to iterate
  202. over all of the available flatpages on the :ref:`current site
  203. <hooking-into-current-site-from-views>`.
  204. Like all custom template tags, you'll need to :ref:`load its custom
  205. tag library <loading-custom-template-libraries>` before you can use
  206. it. After loading the library, you can retrieve all current flatpages
  207. via the :ttag:`get_flatpages` tag:
  208. .. code-block:: html+django
  209. {% load flatpages %}
  210. {% get_flatpages as flatpages %}
  211. <ul>
  212. {% for page in flatpages %}
  213. <li><a href="{{ page.url }}">{{ page.title }}</a></li>
  214. {% endfor %}
  215. </ul>
  216. .. templatetag:: get_flatpages
  217. Displaying ``registration_required`` flatpages
  218. ----------------------------------------------
  219. By default, the :ttag:`get_flatpages` template tag will only show
  220. flatpages that are marked ``registration_required = False``. If you
  221. want to display registration-protected flatpages, you need to specify
  222. an authenticated user using a ``for`` clause.
  223. For example:
  224. .. code-block:: html+django
  225. {% get_flatpages for someuser as about_pages %}
  226. If you provide an anonymous user, :ttag:`get_flatpages` will behave
  227. the same as if you hadn't provided a user -- i.e., it will only show you
  228. public flatpages.
  229. Limiting flatpages by base URL
  230. ------------------------------
  231. An optional argument, ``starts_with``, can be applied to limit the
  232. returned pages to those beginning with a particular base URL. This
  233. argument may be passed as a string, or as a variable to be resolved
  234. from the context.
  235. For example:
  236. .. code-block:: html+django
  237. {% get_flatpages '/about/' as about_pages %}
  238. {% get_flatpages about_prefix as about_pages %}
  239. {% get_flatpages '/about/' for someuser as about_pages %}
  240. Integrating with :mod:`django.contrib.sitemaps`
  241. ===============================================
  242. .. currentmodule:: django.contrib.flatpages.sitemaps
  243. .. class:: FlatPageSitemap
  244. The :class:`sitemaps.FlatPageSitemap
  245. <django.contrib.flatpages.sitemaps.FlatPageSitemap>` class looks at all
  246. publicly visible :mod:`~django.contrib.flatpages` defined for the current
  247. :setting:`SITE_ID` (see the :mod:`sites documentation
  248. <django.contrib.sites>`) and creates an entry in the sitemap. These entries
  249. include only the :attr:`~django.contrib.sitemaps.Sitemap.location`
  250. attribute -- not :attr:`~django.contrib.sitemaps.Sitemap.lastmod`,
  251. :attr:`~django.contrib.sitemaps.Sitemap.changefreq` or
  252. :attr:`~django.contrib.sitemaps.Sitemap.priority`.
  253. Example
  254. -------
  255. Here's an example of a URLconf using :class:`FlatPageSitemap`::
  256. from django.contrib.flatpages.sitemaps import FlatPageSitemap
  257. from django.contrib.sitemaps.views import sitemap
  258. from django.urls import path
  259. urlpatterns = [
  260. # ...
  261. # the sitemap
  262. path(
  263. "sitemap.xml",
  264. sitemap,
  265. {"sitemaps": {"flatpages": FlatPageSitemap}},
  266. name="django.contrib.sitemaps.views.sitemap",
  267. ),
  268. ]