media.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. =================================
  2. Form Assets (the ``Media`` class)
  3. =================================
  4. Rendering an attractive and easy-to-use web form requires more than just
  5. HTML - it also requires CSS stylesheets, and if you want to use fancy widgets,
  6. you may also need to include some JavaScript on each page. The exact
  7. combination of CSS and JavaScript that is required for any given page will
  8. depend upon the widgets that are in use on that page.
  9. This is where asset definitions come in. Django allows you to
  10. associate different files -- like stylesheets and scripts -- with the
  11. forms and widgets that require those assets. For example, if you want
  12. to use a calendar to render DateFields, you can define a custom
  13. Calendar widget. This widget can then be associated with the CSS and
  14. JavaScript that is required to render the calendar. When the Calendar
  15. widget is used on a form, Django is able to identify the CSS and
  16. JavaScript files that are required, and provide the list of file names
  17. in a form suitable for inclusion on your web page.
  18. .. admonition:: Assets and Django Admin
  19. The Django Admin application defines a number of customized
  20. widgets for calendars, filtered selections, and so on. These
  21. widgets define asset requirements, and the Django Admin uses the
  22. custom widgets in place of the Django defaults. The Admin
  23. templates will only include those files that are required to
  24. render the widgets on any given page.
  25. If you like the widgets that the Django Admin application uses,
  26. feel free to use them in your own application! They're all stored
  27. in ``django.contrib.admin.widgets``.
  28. .. admonition:: Which JavaScript toolkit?
  29. Many JavaScript toolkits exist, and many of them include widgets (such
  30. as calendar widgets) that can be used to enhance your application.
  31. Django has deliberately avoided blessing any one JavaScript toolkit.
  32. Each toolkit has its own relative strengths and weaknesses - use
  33. whichever toolkit suits your requirements. Django is able to integrate
  34. with any JavaScript toolkit.
  35. .. _assets-as-a-static-definition:
  36. Assets as a static definition
  37. =============================
  38. The easiest way to define assets is as a static definition. Using this
  39. method, the declaration is an inner ``Media`` class. The properties of the
  40. inner class define the requirements.
  41. Here's an example::
  42. from django import forms
  43. class CalendarWidget(forms.TextInput):
  44. class Media:
  45. css = {
  46. "all": ["pretty.css"],
  47. }
  48. js = ["animations.js", "actions.js"]
  49. This code defines a ``CalendarWidget``, which will be based on ``TextInput``.
  50. Every time the CalendarWidget is used on a form, that form will be directed
  51. to include the CSS file ``pretty.css``, and the JavaScript files
  52. ``animations.js`` and ``actions.js``.
  53. This static definition is converted at runtime into a widget property
  54. named ``media``. The list of assets for a ``CalendarWidget`` instance
  55. can be retrieved through this property:
  56. .. code-block:: pycon
  57. >>> w = CalendarWidget()
  58. >>> print(w.media)
  59. <link href="https://static.example.com/pretty.css" media="all" rel="stylesheet">
  60. <script src="https://static.example.com/animations.js"></script>
  61. <script src="https://static.example.com/actions.js"></script>
  62. Here's a list of all possible ``Media`` options. There are no required options.
  63. ``css``
  64. -------
  65. A dictionary describing the CSS files required for various forms of output
  66. media.
  67. The values in the dictionary should be a tuple/list of file names. See
  68. :ref:`the section on paths <form-asset-paths>` for details of how to
  69. specify paths to these files.
  70. The keys in the dictionary are the output media types. These are the same
  71. types accepted by CSS files in media declarations: 'all', 'aural', 'braille',
  72. 'embossed', 'handheld', 'print', 'projection', 'screen', 'tty' and 'tv'. If
  73. you need to have different stylesheets for different media types, provide
  74. a list of CSS files for each output medium. The following example would
  75. provide two CSS options -- one for the screen, and one for print::
  76. class Media:
  77. css = {
  78. "screen": ["pretty.css"],
  79. "print": ["newspaper.css"],
  80. }
  81. If a group of CSS files are appropriate for multiple output media types,
  82. the dictionary key can be a comma separated list of output media types.
  83. In the following example, TV's and projectors will have the same media
  84. requirements::
  85. class Media:
  86. css = {
  87. "screen": ["pretty.css"],
  88. "tv,projector": ["lo_res.css"],
  89. "print": ["newspaper.css"],
  90. }
  91. If this last CSS definition were to be rendered, it would become the following HTML:
  92. .. code-block:: html+django
  93. <link href="https://static.example.com/pretty.css" media="screen" rel="stylesheet">
  94. <link href="https://static.example.com/lo_res.css" media="tv,projector" rel="stylesheet">
  95. <link href="https://static.example.com/newspaper.css" media="print" rel="stylesheet">
  96. ``js``
  97. ------
  98. A tuple describing the required JavaScript files. See :ref:`the
  99. section on paths <form-asset-paths>` for details of how to specify
  100. paths to these files.
  101. ``extend``
  102. ----------
  103. A boolean defining inheritance behavior for ``Media`` declarations.
  104. By default, any object using a static ``Media`` definition will
  105. inherit all the assets associated with the parent widget. This occurs
  106. regardless of how the parent defines its own requirements. For
  107. example, if we were to extend our basic Calendar widget from the
  108. example above:
  109. .. code-block:: pycon
  110. >>> class FancyCalendarWidget(CalendarWidget):
  111. ... class Media:
  112. ... css = {
  113. ... "all": ["fancy.css"],
  114. ... }
  115. ... js = ["whizbang.js"]
  116. ...
  117. >>> w = FancyCalendarWidget()
  118. >>> print(w.media)
  119. <link href="https://static.example.com/pretty.css" media="all" rel="stylesheet">
  120. <link href="https://static.example.com/fancy.css" media="all" rel="stylesheet">
  121. <script src="https://static.example.com/animations.js"></script>
  122. <script src="https://static.example.com/actions.js"></script>
  123. <script src="https://static.example.com/whizbang.js"></script>
  124. The FancyCalendar widget inherits all the assets from its parent
  125. widget. If you don't want ``Media`` to be inherited in this way, add
  126. an ``extend=False`` declaration to the ``Media`` declaration:
  127. .. code-block:: pycon
  128. >>> class FancyCalendarWidget(CalendarWidget):
  129. ... class Media:
  130. ... extend = False
  131. ... css = {
  132. ... "all": ["fancy.css"],
  133. ... }
  134. ... js = ["whizbang.js"]
  135. ...
  136. >>> w = FancyCalendarWidget()
  137. >>> print(w.media)
  138. <link href="https://static.example.com/fancy.css" media="all" rel="stylesheet">
  139. <script src="https://static.example.com/whizbang.js"></script>
  140. If you require even more control over inheritance, define your assets using a
  141. :ref:`dynamic property <dynamic-property>`. Dynamic properties give you
  142. complete control over which files are inherited, and which are not.
  143. .. _dynamic-property:
  144. ``Media`` as a dynamic property
  145. ===============================
  146. If you need to perform some more sophisticated manipulation of asset
  147. requirements, you can define the ``media`` property directly. This is
  148. done by defining a widget property that returns an instance of
  149. ``forms.Media``. The constructor for ``forms.Media`` accepts ``css``
  150. and ``js`` keyword arguments in the same format as that used in a
  151. static media definition.
  152. For example, the static definition for our Calendar Widget could also
  153. be defined in a dynamic fashion::
  154. class CalendarWidget(forms.TextInput):
  155. @property
  156. def media(self):
  157. return forms.Media(
  158. css={"all": ["pretty.css"]}, js=["animations.js", "actions.js"]
  159. )
  160. See the section on `Media objects`_ for more details on how to construct
  161. return values for dynamic ``media`` properties.
  162. .. _form-asset-paths:
  163. Paths in asset definitions
  164. ==========================
  165. Paths as strings
  166. ----------------
  167. String paths used to specify assets can be either relative or absolute. If a
  168. path starts with ``/``, ``http://`` or ``https://``, it will be
  169. interpreted as an absolute path, and left as-is. All other paths will
  170. be prepended with the value of the appropriate prefix. If the
  171. :mod:`django.contrib.staticfiles` app is installed, it will be used to serve
  172. assets.
  173. Whether or not you use :mod:`django.contrib.staticfiles`, the
  174. :setting:`STATIC_URL` and :setting:`STATIC_ROOT` settings are required to
  175. render a complete web page.
  176. To find the appropriate prefix to use, Django will check if the
  177. :setting:`STATIC_URL` setting is not ``None`` and automatically fall back
  178. to using :setting:`MEDIA_URL`. For example, if the :setting:`MEDIA_URL` for
  179. your site was ``'https://uploads.example.com/'`` and :setting:`STATIC_URL`
  180. was ``None``:
  181. .. code-block:: pycon
  182. >>> from django import forms
  183. >>> class CalendarWidget(forms.TextInput):
  184. ... class Media:
  185. ... css = {
  186. ... "all": ["/css/pretty.css"],
  187. ... }
  188. ... js = ["animations.js", "https://othersite.com/actions.js"]
  189. ...
  190. >>> w = CalendarWidget()
  191. >>> print(w.media)
  192. <link href="/css/pretty.css" media="all" rel="stylesheet">
  193. <script src="https://uploads.example.com/animations.js"></script>
  194. <script src="https://othersite.com/actions.js"></script>
  195. But if :setting:`STATIC_URL` is ``'https://static.example.com/'``:
  196. .. code-block:: pycon
  197. >>> w = CalendarWidget()
  198. >>> print(w.media)
  199. <link href="/css/pretty.css" media="all" rel="stylesheet">
  200. <script src="https://static.example.com/animations.js"></script>
  201. <script src="https://othersite.com/actions.js"></script>
  202. Or if :mod:`~django.contrib.staticfiles` is configured using the
  203. :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`:
  204. .. code-block:: pycon
  205. >>> w = CalendarWidget()
  206. >>> print(w.media)
  207. <link href="/css/pretty.css" media="all" rel="stylesheet">
  208. <script src="https://static.example.com/animations.27e20196a850.js"></script>
  209. <script src="https://othersite.com/actions.js"></script>
  210. Paths as objects
  211. ----------------
  212. Asset paths may also be given as hashable objects implementing an
  213. ``__html__()`` method. The ``__html__()`` method is typically added using the
  214. :func:`~django.utils.html.html_safe` decorator. The object is responsible for
  215. outputting the complete HTML ``<script>`` or ``<link>`` tag content:
  216. .. code-block:: pycon
  217. >>> from django import forms
  218. >>> from django.utils.html import html_safe
  219. >>>
  220. >>> @html_safe
  221. ... class JSPath:
  222. ... def __str__(self):
  223. ... return '<script src="https://example.org/asset.js" defer>'
  224. ...
  225. >>> class SomeWidget(forms.TextInput):
  226. ... class Media:
  227. ... js = [JSPath()]
  228. ...
  229. ``Media`` objects
  230. =================
  231. When you interrogate the ``media`` attribute of a widget or form, the
  232. value that is returned is a ``forms.Media`` object. As we have already
  233. seen, the string representation of a ``Media`` object is the HTML
  234. required to include the relevant files in the ``<head>`` block of your
  235. HTML page.
  236. However, ``Media`` objects have some other interesting properties.
  237. Subsets of assets
  238. -----------------
  239. If you only want files of a particular type, you can use the subscript
  240. operator to filter out a medium of interest. For example:
  241. .. code-block:: pycon
  242. >>> w = CalendarWidget()
  243. >>> print(w.media)
  244. <link href="https://static.example.com/pretty.css" media="all" rel="stylesheet">
  245. <script src="https://static.example.com/animations.js"></script>
  246. <script src="https://static.example.com/actions.js"></script>
  247. >>> print(w.media["css"])
  248. <link href="https://static.example.com/pretty.css" media="all" rel="stylesheet">
  249. When you use the subscript operator, the value that is returned is a
  250. new ``Media`` object -- but one that only contains the media of interest.
  251. Combining ``Media`` objects
  252. ---------------------------
  253. ``Media`` objects can also be added together. When two ``Media`` objects are
  254. added, the resulting ``Media`` object contains the union of the assets
  255. specified by both:
  256. .. code-block:: pycon
  257. >>> from django import forms
  258. >>> class CalendarWidget(forms.TextInput):
  259. ... class Media:
  260. ... css = {
  261. ... "all": ["pretty.css"],
  262. ... }
  263. ... js = ["animations.js", "actions.js"]
  264. ...
  265. >>> class OtherWidget(forms.TextInput):
  266. ... class Media:
  267. ... js = ["whizbang.js"]
  268. ...
  269. >>> w1 = CalendarWidget()
  270. >>> w2 = OtherWidget()
  271. >>> print(w1.media + w2.media)
  272. <link href="https://static.example.com/pretty.css" media="all" rel="stylesheet">
  273. <script src="https://static.example.com/animations.js"></script>
  274. <script src="https://static.example.com/actions.js"></script>
  275. <script src="https://static.example.com/whizbang.js"></script>
  276. .. _form-media-asset-order:
  277. Order of assets
  278. ---------------
  279. The order in which assets are inserted into the DOM is often important. For
  280. example, you may have a script that depends on jQuery. Therefore, combining
  281. ``Media`` objects attempts to preserve the relative order in which assets are
  282. defined in each ``Media`` class.
  283. For example:
  284. .. code-block:: pycon
  285. >>> from django import forms
  286. >>> class CalendarWidget(forms.TextInput):
  287. ... class Media:
  288. ... js = ["jQuery.js", "calendar.js", "noConflict.js"]
  289. ...
  290. >>> class TimeWidget(forms.TextInput):
  291. ... class Media:
  292. ... js = ["jQuery.js", "time.js", "noConflict.js"]
  293. ...
  294. >>> w1 = CalendarWidget()
  295. >>> w2 = TimeWidget()
  296. >>> print(w1.media + w2.media)
  297. <script src="https://static.example.com/jQuery.js"></script>
  298. <script src="https://static.example.com/calendar.js"></script>
  299. <script src="https://static.example.com/time.js"></script>
  300. <script src="https://static.example.com/noConflict.js"></script>
  301. Combining ``Media`` objects with assets in a conflicting order results in a
  302. ``MediaOrderConflictWarning``.
  303. ``Media`` on Forms
  304. ==================
  305. Widgets aren't the only objects that can have ``media`` definitions --
  306. forms can also define ``media``. The rules for ``media`` definitions
  307. on forms are the same as the rules for widgets: declarations can be
  308. static or dynamic; path and inheritance rules for those declarations
  309. are exactly the same.
  310. Regardless of whether you define a ``media`` declaration, *all* Form
  311. objects have a ``media`` property. The default value for this property
  312. is the result of adding the ``media`` definitions for all widgets that
  313. are part of the form:
  314. .. code-block:: pycon
  315. >>> from django import forms
  316. >>> class ContactForm(forms.Form):
  317. ... date = DateField(widget=CalendarWidget)
  318. ... name = CharField(max_length=40, widget=OtherWidget)
  319. ...
  320. >>> f = ContactForm()
  321. >>> f.media
  322. <link href="https://static.example.com/pretty.css" media="all" rel="stylesheet">
  323. <script src="https://static.example.com/animations.js"></script>
  324. <script src="https://static.example.com/actions.js"></script>
  325. <script src="https://static.example.com/whizbang.js"></script>
  326. If you want to associate additional assets with a form -- for example,
  327. CSS for form layout -- add a ``Media`` declaration to the form:
  328. .. code-block:: pycon
  329. >>> class ContactForm(forms.Form):
  330. ... date = DateField(widget=CalendarWidget)
  331. ... name = CharField(max_length=40, widget=OtherWidget)
  332. ... class Media:
  333. ... css = {
  334. ... "all": ["layout.css"],
  335. ... }
  336. ...
  337. >>> f = ContactForm()
  338. >>> f.media
  339. <link href="https://static.example.com/pretty.css" media="all" rel="stylesheet">
  340. <link href="https://static.example.com/layout.css" media="all" rel="stylesheet">
  341. <script src="https://static.example.com/animations.js"></script>
  342. <script src="https://static.example.com/actions.js"></script>
  343. <script src="https://static.example.com/whizbang.js"></script>