media.txt 16 KB

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