| 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 their URLs in the :doc:`URLconf </topics/http/urls>`:: |
| 93 |
|
| 94 |
from django.contrib.flatpages import views |
| 95 |
|
| 96 |
urlpatterns += [ |
| 97 |
path("about-us/", views.flatpage, kwargs={"url": "/about-us/"}, name="about"), |
| 98 |
path("license/", views.flatpage, kwargs={"url": "/license/"}, name="license"), |
| 99 |
] |
| 100 |
|
| 101 |
The ``kwargs`` argument sets the ``url`` value used for the ``FlatPage`` model |
| 102 |
lookup in the flatpage view. |
| 103 |
|
| 104 |
The ``name`` argument allows the URL to be reversed in templates, for example |
| 105 |
using the :ttag:`url` template tag. |
| 106 |
|
| 107 |
Using the middleware |
| 108 |
-------------------- |
| 109 |
|
| 110 |
The :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` |
| 111 |
can do all of the work. |
| 112 |
|
| 113 |
.. class:: FlatpageFallbackMiddleware |
| 114 |
|
| 115 |
Each time any Django application raises a 404 error, this middleware |
| 116 |
checks the flatpages database for the requested URL as a last resort. |
| 117 |
Specifically, it checks for a flatpage with the given URL with a site ID |
| 118 |
that corresponds to the :setting:`SITE_ID` setting. |
| 119 |
|
| 120 |
If it finds a match, it follows this algorithm: |
| 121 |
|
| 122 |
* If the flatpage has a custom template, it loads that template. |
| 123 |
Otherwise, it loads the template :file:`flatpages/default.html`. |
| 124 |
|
| 125 |
* It passes that template a single context variable, ``flatpage``, |
| 126 |
which is the flatpage object. It uses |
| 127 |
:class:`~django.template.RequestContext` in rendering the |
| 128 |
template. |
| 129 |
|
| 130 |
The middleware will only add a trailing slash and redirect (by looking |
| 131 |
at the :setting:`APPEND_SLASH` setting) if the resulting URL refers to |
| 132 |
a valid flatpage. Redirects are permanent (301 status code). |
| 133 |
|
| 134 |
If it doesn't find a match, the request continues to be processed as usual. |
| 135 |
|
| 136 |
The middleware only gets activated for 404s -- not for 500s or responses |
| 137 |
of any other status code. |
| 138 |
|
| 139 |
.. admonition:: Flatpages will not apply view middleware |
| 140 |
|
| 141 |
Because the ``FlatpageFallbackMiddleware`` is applied only after |
| 142 |
URL resolution has failed and produced a 404, the response it |
| 143 |
returns will not apply any :ref:`view middleware <view-middleware>` |
| 144 |
methods. Only requests which are successfully routed to a view via |
| 145 |
normal URL resolution apply view middleware. |
| 146 |
|
| 147 |
Note that the order of :setting:`MIDDLEWARE` matters. Generally, you can put |
| 148 |
:class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` at the |
| 149 |
end of the list. This means it will run first when processing the response, and |
| 150 |
ensures that any other response-processing middleware see the real flatpage |
| 151 |
response rather than the 404. |
| 152 |
|
| 153 |
For more on middleware, read the :doc:`middleware docs |
| 154 |
</topics/http/middleware>`. |
| 155 |
|
| 156 |
.. admonition:: Ensure that your 404 template works |
| 157 |
|
| 158 |
Note that the |
| 159 |
:class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` |
| 160 |
only steps in once another view has successfully produced a 404 response. |
| 161 |
If another view or middleware class attempts to produce a 404 but ends up |
| 162 |
raising an exception instead, the response will become an HTTP 500 |
| 163 |
("Internal Server Error") and the |
| 164 |
:class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` |
| 165 |
will not attempt to serve a flat page. |
| 166 |
|
| 167 |
.. currentmodule:: django.contrib.flatpages.models |
| 168 |
|
| 169 |
How to add, change and delete flatpages |
| 170 |
======================================= |
| 171 |
|
| 172 |
.. warning:: |
| 173 |
|
| 174 |
Permissions to add or edit flatpages should be restricted to trusted users. |
| 175 |
Flatpages are defined by raw HTML and are **not sanitized** by Django. As a |
| 176 |
consequence, a malicious flatpage can lead to various security |
| 177 |
vulnerabilities, including permission escalation. |
| 178 |
|
| 179 |
.. _flatpages-admin: |
| 180 |
|
| 181 |
Via the admin interface |
| 182 |
----------------------- |
| 183 |
|
| 184 |
If you've activated the automatic Django admin interface, you should see a |
| 185 |
"Flatpages" section on the admin index page. Edit flatpages as you edit any |
| 186 |
other object in the system. |
| 187 |
|
| 188 |
The ``FlatPage`` model has an ``enable_comments`` field that isn't used by |
| 189 |
``contrib.flatpages``, but that could be useful for your project or third-party |
| 190 |
apps. It doesn't appear in the admin interface, but you can add it by |
| 191 |
registering a custom ``ModelAdmin`` for ``FlatPage``:: |
| 192 |
|
| 193 |
from django.contrib import admin |
| 194 |
from django.contrib.flatpages.admin import FlatPageAdmin |
| 195 |
from django.contrib.flatpages.models import FlatPage |
| 196 |
from django.utils.translation import gettext_lazy as _ |
| 197 |
|
| 198 |
|
| 199 |
# Define a new FlatPageAdmin |
| 200 |
class FlatPageAdmin(FlatPageAdmin): |
| 201 |
fieldsets = [ |
| 202 |
(None, {"fields": ["url", "title", "content", "sites"]}), |
| 203 |
( |
| 204 |
_("Advanced options"), |
| 205 |
{ |
| 206 |
"classes": ["collapse"], |
| 207 |
"fields": [ |
| 208 |
"enable_comments", |
| 209 |
"registration_required", |
| 210 |
"template_name", |
| 211 |
], |
| 212 |
}, |
| 213 |
), |
| 214 |
] |
| 215 |
|
| 216 |
|
| 217 |
# Re-register FlatPageAdmin |
| 218 |
admin.site.unregister(FlatPage) |
| 219 |
admin.site.register(FlatPage, FlatPageAdmin) |
| 220 |
|
| 221 |
Via the Python API |
| 222 |
------------------ |
| 223 |
|
| 224 |
Flatpages are represented by a standard |
| 225 |
:doc:`Django model </topics/db/models>`, :class:`.FlatPage`. You can access |
| 226 |
flatpage objects via the :doc:`Django database API </topics/db/queries>`. |
| 227 |
|
| 228 |
.. admonition:: Check for duplicate flatpage URLs. |
| 229 |
|
| 230 |
If you add or modify flatpages via your own code, you will likely want to |
| 231 |
check for duplicate flatpage URLs within the same site. The flatpage form |
| 232 |
used in the admin performs this validation check, and can be imported from |
| 233 |
``django.contrib.flatpages.forms.FlatpageForm`` and used in your own |
| 234 |
views. |
| 235 |
|
| 236 |
.. currentmodule:: django.contrib.flatpages |
| 237 |
|
| 238 |
``FlatPage`` model |
| 239 |
================== |
| 240 |
|
| 241 |
.. class:: models.FlatPage |
| 242 |
|
| 243 |
Fields |
| 244 |
------ |
| 245 |
|
| 246 |
:class:`~django.contrib.flatpages.models.FlatPage` objects have the following |
| 247 |
fields: |
| 248 |
|
| 249 |
.. class:: models.FlatPage |
| 250 |
:noindex: |
| 251 |
|
| 252 |
.. attribute:: url |
| 253 |
|
| 254 |
Required. 100 characters or fewer. Indexed for faster lookups. |
| 255 |
|
| 256 |
.. attribute:: title |
| 257 |
|
| 258 |
Required. 200 characters or fewer. |
| 259 |
|
| 260 |
.. attribute:: content |
| 261 |
|
| 262 |
Optional (:attr:`blank=True <django.db.models.Field.blank>`). |
| 263 |
:class:`~django.db.models.TextField` that typically, contains the HTML |
| 264 |
content of the page. |
| 265 |
|
| 266 |
.. attribute:: enable_comments |
| 267 |
|
| 268 |
Boolean. This field is not used by :mod:`~django.contrib.flatpages` by |
| 269 |
default and does not appear in the admin interface. Please see |
| 270 |
:ref:`flatpages admin interface section <flatpages-admin>` for a |
| 271 |
detailed explanation. |
| 272 |
|
| 273 |
.. attribute:: template_name |
| 274 |
|
| 275 |
Optional (:attr:`blank=True <django.db.models.Field.blank>`). 70 |
| 276 |
characters or fewer. Specifies the template used to render the page. |
| 277 |
Defaults to :file:`flatpages/default.html` if not provided. |
| 278 |
|
| 279 |
.. attribute: registration_required |
| 280 |
|
| 281 |
Boolean. When ``True``, restricts the page access to logged-in users |
| 282 |
only. |
| 283 |
|
| 284 |
.. attribute:: sites |
| 285 |
|
| 286 |
Many-to-many relationship to |
| 287 |
:class:`~django.contrib.sites.models.Site`, which determines the |
| 288 |
:doc:`sites </ref/contrib/sites>` the flatpage is available on. |
| 289 |
|
| 290 |
Methods |
| 291 |
------- |
| 292 |
|
| 293 |
.. class:: models.FlatPage |
| 294 |
:noindex: |
| 295 |
|
| 296 |
.. method:: get_absolute_url() |
| 297 |
|
| 298 |
Returns the relative URL path of the page based on the |
| 299 |
:attr:`~django.contrib.flatpages.models.FlatPage.url` attribute. |
| 300 |
|
| 301 |
Flatpage templates |
| 302 |
================== |
| 303 |
|
| 304 |
By default, flatpages are rendered via the template |
| 305 |
:file:`flatpages/default.html`, but you can override that for a |
| 306 |
particular flatpage: in the admin, a collapsed fieldset titled |
| 307 |
"Advanced options" (clicking will expand it) contains a field for |
| 308 |
specifying a template name. If you're creating a flat page via the |
| 309 |
Python API you can set the template name as the field ``template_name`` on the |
| 310 |
``FlatPage`` object. |
| 311 |
|
| 312 |
Creating the :file:`flatpages/default.html` template is your responsibility; |
| 313 |
in your template directory, create a :file:`flatpages` directory containing a |
| 314 |
file :file:`default.html`. |
| 315 |
|
| 316 |
Flatpage templates are passed a single context variable, ``flatpage``, |
| 317 |
which is the flatpage object. |
| 318 |
|
| 319 |
Here's a sample :file:`flatpages/default.html` template: |
| 320 |
|
| 321 |
.. code-block:: html+django |
| 322 |
|
| 323 |
<!DOCTYPE html> |
| 324 |
<html lang="en"> |
| 325 |
<head> |
| 326 |
<title>{{ flatpage.title }}</title> |
| 327 |
</head> |
| 328 |
<body> |
| 329 |
{{ flatpage.content }} |
| 330 |
</body> |
| 331 |
</html> |
| 332 |
|
| 333 |
Since you're already entering raw HTML into the admin page for a flatpage, |
| 334 |
both ``flatpage.title`` and ``flatpage.content`` are marked as **not** |
| 335 |
requiring :ref:`automatic HTML escaping <automatic-html-escaping>` in the |
| 336 |
template. |
| 337 |
|
| 338 |
Getting a list of :class:`~django.contrib.flatpages.models.FlatPage` objects in your templates |
| 339 |
============================================================================================== |
| 340 |
|
| 341 |
The flatpages app provides a template tag that allows you to iterate |
| 342 |
over all of the available flatpages on the :ref:`current site |
| 343 |
<hooking-into-current-site-from-views>`. |
| 344 |
|
| 345 |
Like all custom template tags, you'll need to :ref:`load its custom |
| 346 |
tag library <loading-custom-template-libraries>` before you can use |
| 347 |
it. After loading the library, you can retrieve all current flatpages |
| 348 |
via the :ttag:`get_flatpages` tag: |
| 349 |
|
| 350 |
.. code-block:: html+django |
| 351 |
|
| 352 |
{% load flatpages %} |
| 353 |
{% get_flatpages as flatpages %} |
| 354 |
<ul> |
| 355 |
{% for page in flatpages %} |
| 356 |
<li><a href="{{ page.url }}">{{ page.title }}</a></li> |
| 357 |
{% endfor %} |
| 358 |
</ul> |
| 359 |
|
| 360 |
.. templatetag:: get_flatpages |
| 361 |
|
| 362 |
Displaying ``registration_required`` flatpages |
| 363 |
---------------------------------------------- |
| 364 |
|
| 365 |
By default, the :ttag:`get_flatpages` template tag will only show |
| 366 |
flatpages that are marked ``registration_required = False``. If you |
| 367 |
want to display registration-protected flatpages, you need to specify |
| 368 |
an authenticated user using a ``for`` clause. |
| 369 |
|
| 370 |
For example: |
| 371 |
|
| 372 |
.. code-block:: html+django |
| 373 |
|
| 374 |
{% get_flatpages for someuser as about_pages %} |
| 375 |
|
| 376 |
If you provide an anonymous user, :ttag:`get_flatpages` will behave |
| 377 |
the same as if you hadn't provided a user -- i.e., it will only show you |
| 378 |
public flatpages. |
| 379 |
|
| 380 |
Limiting flatpages by base URL |
| 381 |
------------------------------ |
| 382 |
|
| 383 |
An optional argument, ``starts_with``, can be applied to limit the |
| 384 |
returned pages to those beginning with a particular base URL. This |
| 385 |
argument may be passed as a string, or as a variable to be resolved |
| 386 |
from the context. |
| 387 |
|
| 388 |
For example: |
| 389 |
|
| 390 |
.. code-block:: html+django |
| 391 |
|
| 392 |
{% get_flatpages '/about/' as about_pages %} |
| 393 |
{% get_flatpages about_prefix as about_pages %} |
| 394 |
{% get_flatpages '/about/' for someuser as about_pages %} |
| 395 |
|
| 396 |
Integrating with :mod:`django.contrib.sitemaps` |
| 397 |
=============================================== |
| 398 |
|
| 399 |
.. currentmodule:: django.contrib.flatpages.sitemaps |
| 400 |
|
| 401 |
.. class:: FlatPageSitemap |
| 402 |
|
| 403 |
The :class:`sitemaps.FlatPageSitemap |
| 404 |
<django.contrib.flatpages.sitemaps.FlatPageSitemap>` class looks at all |
| 405 |
publicly visible :mod:`~django.contrib.flatpages` defined for the current |
| 406 |
:setting:`SITE_ID` (see the :mod:`sites documentation |
| 407 |
<django.contrib.sites>`) and creates an entry in the sitemap. These entries |
| 408 |
include only the :attr:`~django.contrib.sitemaps.Sitemap.location` |
| 409 |
attribute -- not :attr:`~django.contrib.sitemaps.Sitemap.lastmod`, |
| 410 |
:attr:`~django.contrib.sitemaps.Sitemap.changefreq` or |
| 411 |
:attr:`~django.contrib.sitemaps.Sitemap.priority`. |
| 412 |
|
| 413 |
Example |
| 414 |
------- |
| 415 |
|
| 416 |
Here's an example of a URLconf using :class:`FlatPageSitemap`:: |
| 417 |
|
| 418 |
from django.contrib.flatpages.sitemaps import FlatPageSitemap |
| 419 |
from django.contrib.sitemaps.views import sitemap |
| 420 |
from django.urls import path |
| 421 |
|
| 422 |
urlpatterns = [ |
| 423 |
# ... |
| 424 |
# the sitemap |
| 425 |
path( |
| 426 |
"sitemap.xml", |
| 427 |
sitemap, |
| 428 |
{"sitemaps": {"flatpages": FlatPageSitemap}}, |
| 429 |
name="django.contrib.sitemaps.views.sitemap", |
| 430 |
), |
| 431 |
] |