media.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. >>> w = CalendarWidget()
  57. >>> print(w.media)
  58. <link href="http://static.example.com/pretty.css" media="all" rel="stylesheet">
  59. <script src="http://static.example.com/animations.js"></script>
  60. <script src="http://static.example.com/actions.js"></script>
  61. Here's a list of all possible ``Media`` options. There are no required options.
  62. ``css``
  63. -------
  64. A dictionary describing the CSS files required for various forms of output
  65. media.
  66. The values in the dictionary should be a tuple/list of file names. See
  67. :ref:`the section on paths <form-asset-paths>` for details of how to
  68. specify paths to these files.
  69. The keys in the dictionary are the output media types. These are the same
  70. types accepted by CSS files in media declarations: 'all', 'aural', 'braille',
  71. 'embossed', 'handheld', 'print', 'projection', 'screen', 'tty' and 'tv'. If
  72. you need to have different stylesheets for different media types, provide
  73. a list of CSS files for each output medium. The following example would
  74. provide two CSS options -- one for the screen, and one for print::
  75. class Media:
  76. css = {
  77. 'screen': ('pretty.css',),
  78. 'print': ('newspaper.css',)
  79. }
  80. If a group of CSS files are appropriate for multiple output media types,
  81. the dictionary key can be a comma separated list of output media types.
  82. In the following example, TV's and projectors will have the same media
  83. requirements::
  84. class Media:
  85. css = {
  86. 'screen': ('pretty.css',),
  87. 'tv,projector': ('lo_res.css',),
  88. 'print': ('newspaper.css',)
  89. }
  90. If this last CSS definition were to be rendered, it would become the following HTML::
  91. <link href="http://static.example.com/pretty.css" media="screen" rel="stylesheet">
  92. <link href="http://static.example.com/lo_res.css" media="tv,projector" rel="stylesheet">
  93. <link href="http://static.example.com/newspaper.css" media="print" rel="stylesheet">
  94. .. versionchanged:: 4.1
  95. In older versions, the ``type="text/css"`` attribute is included in CSS
  96. links.
  97. ``js``
  98. ------
  99. A tuple describing the required JavaScript files. See :ref:`the
  100. section on paths <form-asset-paths>` for details of how to specify
  101. paths to these files.
  102. ``extend``
  103. ----------
  104. A boolean defining inheritance behavior for ``Media`` declarations.
  105. By default, any object using a static ``Media`` definition will
  106. inherit all the assets associated with the parent widget. This occurs
  107. regardless of how the parent defines its own requirements. For
  108. example, if we were to extend our basic Calendar widget from the
  109. example above::
  110. >>> class FancyCalendarWidget(CalendarWidget):
  111. ... class Media:
  112. ... css = {
  113. ... 'all': ('fancy.css',)
  114. ... }
  115. ... js = ('whizbang.js',)
  116. >>> w = FancyCalendarWidget()
  117. >>> print(w.media)
  118. <link href="http://static.example.com/pretty.css" media="all" rel="stylesheet">
  119. <link href="http://static.example.com/fancy.css" media="all" rel="stylesheet">
  120. <script src="http://static.example.com/animations.js"></script>
  121. <script src="http://static.example.com/actions.js"></script>
  122. <script src="http://static.example.com/whizbang.js"></script>
  123. The FancyCalendar widget inherits all the assets from its parent
  124. widget. If you don't want ``Media`` to be inherited in this way, add
  125. an ``extend=False`` declaration to the ``Media`` declaration::
  126. >>> class FancyCalendarWidget(CalendarWidget):
  127. ... class Media:
  128. ... extend = False
  129. ... css = {
  130. ... 'all': ('fancy.css',)
  131. ... }
  132. ... js = ('whizbang.js',)
  133. >>> w = FancyCalendarWidget()
  134. >>> print(w.media)
  135. <link href="http://static.example.com/fancy.css" media="all" rel="stylesheet">
  136. <script src="http://static.example.com/whizbang.js"></script>
  137. If you require even more control over inheritance, define your assets using a
  138. :ref:`dynamic property <dynamic-property>`. Dynamic properties give you
  139. complete control over which files are inherited, and which are not.
  140. .. _dynamic-property:
  141. ``Media`` as a dynamic property
  142. ===============================
  143. If you need to perform some more sophisticated manipulation of asset
  144. requirements, you can define the ``media`` property directly. This is
  145. done by defining a widget property that returns an instance of
  146. ``forms.Media``. The constructor for ``forms.Media`` accepts ``css``
  147. and ``js`` keyword arguments in the same format as that used in a
  148. static media definition.
  149. For example, the static definition for our Calendar Widget could also
  150. be defined in a dynamic fashion::
  151. class CalendarWidget(forms.TextInput):
  152. @property
  153. def media(self):
  154. return forms.Media(css={'all': ('pretty.css',)},
  155. js=('animations.js', 'actions.js'))
  156. See the section on `Media objects`_ for more details on how to construct
  157. return values for dynamic ``media`` properties.
  158. .. _form-asset-paths:
  159. Paths in asset definitions
  160. ==========================
  161. Paths used to specify assets can be either relative or absolute. If a
  162. path starts with ``/``, ``http://`` or ``https://``, it will be
  163. interpreted as an absolute path, and left as-is. All other paths will
  164. be prepended with the value of the appropriate prefix. If the
  165. :mod:`django.contrib.staticfiles` app is installed, it will be used to serve
  166. assets.
  167. Whether or not you use :mod:`django.contrib.staticfiles`, the
  168. :setting:`STATIC_URL` and :setting:`STATIC_ROOT` settings are required to
  169. render a complete web page.
  170. To find the appropriate prefix to use, Django will check if the
  171. :setting:`STATIC_URL` setting is not ``None`` and automatically fall back
  172. to using :setting:`MEDIA_URL`. For example, if the :setting:`MEDIA_URL` for
  173. your site was ``'http://uploads.example.com/'`` and :setting:`STATIC_URL`
  174. was ``None``::
  175. >>> from django import forms
  176. >>> class CalendarWidget(forms.TextInput):
  177. ... class Media:
  178. ... css = {
  179. ... 'all': ('/css/pretty.css',),
  180. ... }
  181. ... js = ('animations.js', 'http://othersite.com/actions.js')
  182. >>> w = CalendarWidget()
  183. >>> print(w.media)
  184. <link href="/css/pretty.css" media="all" rel="stylesheet">
  185. <script src="http://uploads.example.com/animations.js"></script>
  186. <script src="http://othersite.com/actions.js"></script>
  187. But if :setting:`STATIC_URL` is ``'http://static.example.com/'``::
  188. >>> w = CalendarWidget()
  189. >>> print(w.media)
  190. <link href="/css/pretty.css" media="all" rel="stylesheet">
  191. <script src="http://static.example.com/animations.js"></script>
  192. <script src="http://othersite.com/actions.js"></script>
  193. Or if :mod:`~django.contrib.staticfiles` is configured using the
  194. :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`::
  195. >>> w = CalendarWidget()
  196. >>> print(w.media)
  197. <link href="/css/pretty.css" media="all" rel="stylesheet">
  198. <script src="https://static.example.com/animations.27e20196a850.js"></script>
  199. <script src="http://othersite.com/actions.js"></script>
  200. ``Media`` objects
  201. =================
  202. When you interrogate the ``media`` attribute of a widget or form, the
  203. value that is returned is a ``forms.Media`` object. As we have already
  204. seen, the string representation of a ``Media`` object is the HTML
  205. required to include the relevant files in the ``<head>`` block of your
  206. HTML page.
  207. However, ``Media`` objects have some other interesting properties.
  208. Subsets of assets
  209. -----------------
  210. If you only want files of a particular type, you can use the subscript
  211. operator to filter out a medium of interest. For example::
  212. >>> w = CalendarWidget()
  213. >>> print(w.media)
  214. <link href="http://static.example.com/pretty.css" media="all" rel="stylesheet">
  215. <script src="http://static.example.com/animations.js"></script>
  216. <script src="http://static.example.com/actions.js"></script>
  217. >>> print(w.media['css'])
  218. <link href="http://static.example.com/pretty.css" media="all" rel="stylesheet">
  219. When you use the subscript operator, the value that is returned is a
  220. new ``Media`` object -- but one that only contains the media of interest.
  221. Combining ``Media`` objects
  222. ---------------------------
  223. ``Media`` objects can also be added together. When two ``Media`` objects are
  224. added, the resulting ``Media`` object contains the union of the assets
  225. specified by both::
  226. >>> from django import forms
  227. >>> class CalendarWidget(forms.TextInput):
  228. ... class Media:
  229. ... css = {
  230. ... 'all': ('pretty.css',)
  231. ... }
  232. ... js = ('animations.js', 'actions.js')
  233. >>> class OtherWidget(forms.TextInput):
  234. ... class Media:
  235. ... js = ('whizbang.js',)
  236. >>> w1 = CalendarWidget()
  237. >>> w2 = OtherWidget()
  238. >>> print(w1.media + w2.media)
  239. <link href="http://static.example.com/pretty.css" media="all" rel="stylesheet">
  240. <script src="http://static.example.com/animations.js"></script>
  241. <script src="http://static.example.com/actions.js"></script>
  242. <script src="http://static.example.com/whizbang.js"></script>
  243. .. _form-media-asset-order:
  244. Order of assets
  245. ---------------
  246. The order in which assets are inserted into the DOM is often important. For
  247. example, you may have a script that depends on jQuery. Therefore, combining
  248. ``Media`` objects attempts to preserve the relative order in which assets are
  249. defined in each ``Media`` class.
  250. For example::
  251. >>> from django import forms
  252. >>> class CalendarWidget(forms.TextInput):
  253. ... class Media:
  254. ... js = ('jQuery.js', 'calendar.js', 'noConflict.js')
  255. >>> class TimeWidget(forms.TextInput):
  256. ... class Media:
  257. ... js = ('jQuery.js', 'time.js', 'noConflict.js')
  258. >>> w1 = CalendarWidget()
  259. >>> w2 = TimeWidget()
  260. >>> print(w1.media + w2.media)
  261. <script src="http://static.example.com/jQuery.js"></script>
  262. <script src="http://static.example.com/calendar.js"></script>
  263. <script src="http://static.example.com/time.js"></script>
  264. <script src="http://static.example.com/noConflict.js"></script>
  265. Combining ``Media`` objects with assets in a conflicting order results in a
  266. ``MediaOrderConflictWarning``.
  267. ``Media`` on Forms
  268. ==================
  269. Widgets aren't the only objects that can have ``media`` definitions --
  270. forms can also define ``media``. The rules for ``media`` definitions
  271. on forms are the same as the rules for widgets: declarations can be
  272. static or dynamic; path and inheritance rules for those declarations
  273. are exactly the same.
  274. Regardless of whether you define a ``media`` declaration, *all* Form
  275. objects have a ``media`` property. The default value for this property
  276. is the result of adding the ``media`` definitions for all widgets that
  277. are part of the form::
  278. >>> from django import forms
  279. >>> class ContactForm(forms.Form):
  280. ... date = DateField(widget=CalendarWidget)
  281. ... name = CharField(max_length=40, widget=OtherWidget)
  282. >>> f = ContactForm()
  283. >>> f.media
  284. <link href="http://static.example.com/pretty.css" media="all" rel="stylesheet">
  285. <script src="http://static.example.com/animations.js"></script>
  286. <script src="http://static.example.com/actions.js"></script>
  287. <script src="http://static.example.com/whizbang.js"></script>
  288. If you want to associate additional assets with a form -- for example,
  289. CSS for form layout -- add a ``Media`` declaration to the form::
  290. >>> class ContactForm(forms.Form):
  291. ... date = DateField(widget=CalendarWidget)
  292. ... name = CharField(max_length=40, widget=OtherWidget)
  293. ...
  294. ... class Media:
  295. ... css = {
  296. ... 'all': ('layout.css',)
  297. ... }
  298. >>> f = ContactForm()
  299. >>> f.media
  300. <link href="http://static.example.com/pretty.css" media="all" rel="stylesheet">
  301. <link href="http://static.example.com/layout.css" media="all" rel="stylesheet">
  302. <script src="http://static.example.com/animations.js"></script>
  303. <script src="http://static.example.com/actions.js"></script>
  304. <script src="http://static.example.com/whizbang.js"></script>