2
0

flatpages.txt 12 KB

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