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