Skip to content

Commit 67fef66

Browse files
chipx86cyberdelia
authored andcommitted
Add support for using Pipeline CSS/JS packages in forms and widgets. (jazzband#620)
Django allows forms and widgets to define the CSS or JavaScript files needed on the page, automatically including those files in the administration UI. This works fine for standalone media files, but weren't an option for Pipeline packages. This change introduces a branch new `PipelineFormMedia` class that a form or widget's Media class can inherit from. The Media class can then define `css_packages` or `js_packages` attributes that work just like the standard `css`/`js` attributes but reference package names instead of individual files. Upon accessing the `css` or `js` attributes, the files defined in the packages will be collected/processed just like with the template tags and the resulting filenames returned for use in the page. Using this, any page compatible with Django's form media support will work automatically with any form or widget that wants to use Pipeline packages, without any modifications to templates or any other workarounds that were needed before. This implements issue jazzband#154.
1 parent fa21ba5 commit 67fef66

File tree

3 files changed

+516
-0
lines changed

3 files changed

+516
-0
lines changed

docs/usage.rst

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,49 @@ with the name “scripts”, you would use the following code to output them all
4040
{% stylesheet 'stats' %}
4141
{% javascript 'scripts' %}
4242

43+
44+
Form Media
45+
==========
46+
47+
Django forms and widgets can specify individual CSS or JavaScript files to
48+
include on a page by defining a ``Form.Media`` class with ``css`` and ``js``
49+
attributes.
50+
51+
Pipeline builds upon this by allowing packages to be listed in
52+
``css_packages`` and ``js_packages``. This is equivalent to manually including
53+
these packages in a page's template using the template tags.
54+
55+
To use these, just have your form or widget's ``Media`` class inherit from
56+
``pipeline.forms.PipelineFormMedia`` and define ``css_packages`` and
57+
``js_packages``. You can also continue to reference individual CSS/JavaScript
58+
files using the original ``css``/``js`` attributes, if needed.
59+
60+
Note that unlike the template tags, you cannot customize the HTML for
61+
referencing these files. The ``pipeline/css.html`` and ``pipeline/js.html``
62+
files will not be used. Django takes care of generating the HTML for form and
63+
widget media.
64+
65+
66+
Example
67+
-------
68+
69+
.. code-block:: python
70+
71+
from django import forms
72+
from pipeline.forms import PipelineFormMedia
73+
74+
75+
class MyForm(forms.Form):
76+
...
77+
78+
class Media(PipelineFormMedia):
79+
css_packages = {
80+
'all': ('my-styles',)
81+
}
82+
js_packages = ('my-scripts',)
83+
js = ('https://cdn.example.com/some-script.js',)
84+
85+
4386
Collect static
4487
==============
4588

pipeline/forms.py

Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
"""Support for referencing Pipeline packages in forms and widgets."""
2+
3+
from __future__ import unicode_literals
4+
5+
from django.contrib.staticfiles.storage import staticfiles_storage
6+
from django.utils import six
7+
from django.utils.functional import cached_property
8+
9+
from .collector import default_collector
10+
from .conf import settings
11+
from .packager import Packager
12+
13+
14+
class PipelineFormMediaProperty(object):
15+
"""A property that converts Pipeline packages to lists of files.
16+
17+
This is used behind the scenes for any Media classes that subclass
18+
:py:class:`PipelineFormMedia`. When accessed, it converts any Pipeline
19+
packages into lists of media files and returns or forwards on lookups to
20+
that list.
21+
"""
22+
23+
def __init__(self, get_media_files_func, media_cls, extra_files):
24+
"""Initialize the property.
25+
26+
Args:
27+
get_media_files_func (callable):
28+
The function to call to generate the media files.
29+
30+
media_cls (type):
31+
The Media class owning the property.
32+
33+
extra_files (object):
34+
Files listed in the original ``css`` or ``js`` attribute on
35+
the Media class.
36+
"""
37+
self._get_media_files_func = get_media_files_func
38+
self._media_cls = media_cls
39+
self._extra_files = extra_files
40+
41+
@cached_property
42+
def _media_files(self):
43+
"""The media files represented by the property."""
44+
return self._get_media_files_func(self._media_cls, self._extra_files)
45+
46+
def __get__(self, *args, **kwargs):
47+
"""Return the media files when accessed as an attribute.
48+
49+
This is called when accessing the attribute directly through the
50+
Media class (for example, ``Media.css``). It returns the media files
51+
directly.
52+
53+
Args:
54+
*args (tuple, unused):
55+
Unused positional arguments.
56+
57+
**kwargs (dict, unused):
58+
Unused keyword arguments.
59+
60+
Returns:
61+
object:
62+
The list or dictionary containing the media files definition.
63+
"""
64+
return self._media_files
65+
66+
def __getattr__(self, attr_name):
67+
"""Return an attribute on the media files definition.
68+
69+
This is called when accessing an attribute that doesn't otherwise
70+
exist in the property's dictionary. The call is forwarded onto the
71+
media files definition.
72+
73+
Args:
74+
attr_name (unicode):
75+
The attribute name.
76+
77+
Returns:
78+
object:
79+
The attribute value.
80+
81+
Raises:
82+
AttributeError:
83+
An attribute with this name could not be found.
84+
"""
85+
return getattr(self._media_files, attr_name)
86+
87+
def __iter__(self):
88+
"""Iterate through the media files definition.
89+
90+
This is called when attempting to iterate over this property. It
91+
iterates over the media files definition instead.
92+
93+
Yields:
94+
object:
95+
Each entry in the media files definition.
96+
"""
97+
return iter(self._media_files)
98+
99+
100+
class PipelineFormMediaMetaClass(type):
101+
"""Metaclass for the PipelineFormMedia class.
102+
103+
This is responsible for converting CSS/JavaScript packages defined in
104+
Pipeline into lists of files to include on a page. It handles access to the
105+
:py:attr:`css` and :py:attr:`js` attributes on the class, generating a
106+
list of files to return based on the Pipelined packages and individual
107+
files listed in the :py:attr:`css`/:py:attr:`css_packages` or
108+
:py:attr:`js`/:py:attr:`js_packages` attributes.
109+
"""
110+
111+
def __new__(cls, name, bases, attrs):
112+
"""Construct the class.
113+
114+
Args:
115+
name (bytes):
116+
The name of the class.
117+
118+
bases (tuple):
119+
The base classes for the class.
120+
121+
attrs (dict):
122+
The attributes going into the class.
123+
124+
Returns:
125+
type:
126+
The new class.
127+
"""
128+
new_class = super(PipelineFormMediaMetaClass, cls).__new__(
129+
cls, name, bases, attrs)
130+
131+
# If we define any packages, we'll need to use our special
132+
# PipelineFormMediaProperty class. We use this instead of intercepting
133+
# in __getattribute__ because Django does not access them through
134+
# normal properpty access. Instead, grabs the Media class's __dict__
135+
# and accesses them from there. By using these special properties, we
136+
# can handle direct access (Media.css) and dictionary-based access
137+
# (Media.__dict__['css']).
138+
if 'css_packages' in attrs:
139+
new_class.css = PipelineFormMediaProperty(
140+
cls._get_css_files, new_class, attrs.get('css') or {})
141+
142+
if 'js_packages' in attrs:
143+
new_class.js = PipelineFormMediaProperty(
144+
cls._get_js_files, new_class, attrs.get('js') or [])
145+
146+
return new_class
147+
148+
def _get_css_files(cls, extra_files):
149+
"""Return all CSS files from the Media class.
150+
151+
Args:
152+
extra_files (dict):
153+
The contents of the Media class's original :py:attr:`css`
154+
attribute, if one was provided.
155+
156+
Returns:
157+
dict:
158+
The CSS media types and files to return for the :py:attr:`css`
159+
attribute.
160+
"""
161+
packager = Packager()
162+
css_packages = getattr(cls, 'css_packages', {})
163+
164+
return dict(
165+
(media_target,
166+
cls._get_media_files(packager=packager,
167+
media_packages=media_packages,
168+
media_type='css',
169+
extra_files=extra_files.get(media_target,
170+
[])))
171+
for media_target, media_packages in six.iteritems(css_packages)
172+
)
173+
174+
def _get_js_files(cls, extra_files):
175+
"""Return all JavaScript files from the Media class.
176+
177+
Args:
178+
extra_files (list):
179+
The contents of the Media class's original :py:attr:`js`
180+
attribute, if one was provided.
181+
182+
Returns:
183+
list:
184+
The JavaScript files to return for the :py:attr:`js` attribute.
185+
"""
186+
return cls._get_media_files(
187+
packager=Packager(),
188+
media_packages=getattr(cls, 'js_packages', {}),
189+
media_type='js',
190+
extra_files=extra_files)
191+
192+
def _get_media_files(cls, packager, media_packages, media_type,
193+
extra_files):
194+
"""Return source or output media files for a list of packages.
195+
196+
This will go through the media files belonging to the provided list
197+
of packages referenced in a Media class and return the output files
198+
(if Pipeline is enabled) or the source files (if not enabled).
199+
200+
Args:
201+
packager (pipeline.packager.Packager):
202+
The packager responsible for media compilation for this type
203+
of package.
204+
205+
media_packages (list of unicode):
206+
The list of media packages referenced in Media to compile or
207+
return.
208+
209+
extra_files (list of unicode):
210+
The list of extra files to include in the result. This would
211+
be the list stored in the Media class's original :py:attr:`css`
212+
or :py:attr:`js` attributes.
213+
214+
Returns:
215+
list:
216+
The list of media files for the given packages.
217+
"""
218+
source_files = list(extra_files)
219+
220+
if (not settings.PIPELINE_ENABLED and
221+
settings.PIPELINE_COLLECTOR_ENABLED):
222+
default_collector.collect()
223+
224+
for media_package in media_packages:
225+
package = packager.package_for(media_type, media_package)
226+
227+
if settings.PIPELINE_ENABLED:
228+
source_files.append(
229+
staticfiles_storage.url(package.output_filename))
230+
else:
231+
source_files += packager.compile(package.paths)
232+
233+
return source_files
234+
235+
236+
@six.add_metaclass(PipelineFormMediaMetaClass)
237+
class PipelineFormMedia(object):
238+
"""Base class for form or widget Media classes that use Pipeline packages.
239+
240+
Forms or widgets that need custom CSS or JavaScript media on a page can
241+
define a standard :py:class:`Media` class that subclasses this class,
242+
listing the CSS or JavaScript packages in :py:attr:`css_packages` and
243+
:py:attr:`js_packages` attributes. These are formatted the same as the
244+
standard :py:attr:`css` and :py:attr:`js` attributes, but reference
245+
Pipeline package names instead of individual source files.
246+
247+
If Pipeline is enabled, these will expand to the output files for the
248+
packages. Otherwise, these will expand to the list of source files for the
249+
packages.
250+
251+
Subclasses can also continue to define :py:attr:`css` and :py:attr:`js`
252+
attributes, which will be returned along with the other output/source
253+
files.
254+
255+
Example:
256+
257+
from django import forms
258+
from pipeline.forms import PipelineFormMedia
259+
260+
261+
class MyForm(forms.Media):
262+
...
263+
264+
class Media(PipelineFormMedia):
265+
css_packages = {
266+
'all': ('my-form-styles-package',
267+
'other-form-styles-package'),
268+
'print': ('my-form-print-styles-package',),
269+
}
270+
271+
js_packages = ('my-form-scripts-package',)
272+
js = ('some-file.js',)
273+
"""

0 commit comments

Comments
 (0)