media.txt 14 KB

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