From 36f0556de03a65f35f7c69e130bc853c1e01e7a5 Mon Sep 17 00:00:00 2001
From: dmpayton <derek.payton@gmail.com>
Date: Tue, 20 Nov 2012 15:34:44 -0800
Subject: [PATCH] Allow inline JS/CSS in forms.Media (#13978)

---
 django/forms/widgets.py                    |   44 ++++++++++++++++++++--------
 docs/topics/forms/media.txt                |   37 +++++++++++++++++++++++
 tests/regressiontests/forms/tests/media.py |   37 +++++++++++++++++++++++
 3 files changed, 106 insertions(+), 12 deletions(-)

diff --git a/django/forms/widgets.py b/django/forms/widgets.py
index c761ea8..65e59e2 100644
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -34,6 +34,16 @@
 
 @python_2_unicode_compatible
 class Media(object):
+    class Inline(object):
+        def __init__(self, content):
+            self.content = content
+
+        def __eq__(self, other):
+            return (
+                type(self) is type(other) and
+                self.content == other.content
+            )
+
     def __init__(self, media=None, **kwargs):
         if media:
             media_attrs = media.__dict__
@@ -57,16 +67,26 @@ def render(self):
         return mark_safe('\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
 
     def render_js(self):
-        return [format_html('<script type="text/javascript" src="{0}"></script>', self.absolute_path(path)) for path in self._js]
+        html = []
+        for script in self._js:
+            if isinstance(script, self.Inline):
+                html.append(format_html('<script type="text/javascript">{0}</script>', mark_safe(script.content)))
+            else:
+                html.append(format_html('<script type="text/javascript" src="{0}"></script>', self.absolute_path(script)))
+        return html
 
     def render_css(self):
         # To keep rendering order consistent, we can't just iterate over items().
         # We need to sort the keys, and iterate over the sorted list.
+        html = []
         media = sorted(self._css.keys())
-        return chain(*[
-                [format_html('<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />', self.absolute_path(path), medium)
-                    for path in self._css[medium]]
-                for medium in media])
+        for medium in media:
+            for style in self._css[medium]:
+                if isinstance(style, self.Inline):
+                    html.append(format_html('<style type="text/css" media="{0}">{1}</style>', medium, mark_safe(style.content)))
+                else:
+                    html.append(format_html('<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />', self.absolute_path(style), medium))
+        return html
 
     def absolute_path(self, path, prefix=None):
         if path.startswith(('http://', 'https://', '/')):
@@ -87,16 +107,16 @@ def __getitem__(self, name):
 
     def add_js(self, data):
         if data:
-            for path in data:
-                if path not in self._js:
-                    self._js.append(path)
+            for script in data:
+                if script not in self._js:
+                    self._js.append(script)
 
     def add_css(self, data):
         if data:
-            for medium, paths in data.items():
-                for path in paths:
-                    if not self._css.get(medium) or path not in self._css[medium]:
-                        self._css.setdefault(medium, []).append(path)
+            for medium, styles in data.items():
+                for style in styles:
+                    if not self._css.get(medium) or style not in self._css[medium]:
+                        self._css.setdefault(medium, []).append(style)
 
     def __add__(self, other):
         combined = Media()
diff --git a/docs/topics/forms/media.txt b/docs/topics/forms/media.txt
index 98e70e5..34d5f89 100644
--- a/docs/topics/forms/media.txt
+++ b/docs/topics/forms/media.txt
@@ -167,6 +167,43 @@ If you require even more control over media inheritance, define your media
 using a :ref:`dynamic property <dynamic-property>`. Dynamic properties give
 you complete control over which media files are inherited, and which are not.
 
+Specifying inline media
+-----------------------
+
+.. versionadded:: 1.5
+
+At some point you may run into a situation that calls for a bit of inline CSS
+or JavaScript, such as initializing a JavaScript plugin. To do this, simply
+pass your inline code as a ``forms.Media.Inline`` object in the Media class::
+
+    >>> class FancyCalendarWidget(CalendarWidget):
+    ...     class Media:
+    ...         css = {
+    ...             'all': ('fancy.css',)
+    ...         }
+    ...         js = (
+    ...             'whizbang.js',
+    ...             forms.Media.Inline('init_fancification();'),
+    ...         )
+
+    >>> w = FancyCalendarWidget()
+    >>> print(w.media)
+    <link href="/static/fancy.css" type="text/css" media="all" rel="stylesheet" />
+    <script type="text/javascript" src="/static/whizbang.js"></script>
+    <script type="text/javascript">init_fancification();</script>
+
+Inline CSS works the same way::
+
+    >>> class HoneypotWidget(forms.TextInput):
+    ...     class Media:
+    ...         css = {
+    ...             'all': (forms.Media.Inline(".honeypot_row { display: none; }"),)
+    ...         }
+
+    >>> w = HoneypotWidget()
+    >>> print(w.media)
+    <style type="text/css" media="all">.honeypot_row { display: none; }</style>
+
 .. _dynamic-property:
 
 Media as a dynamic property
diff --git a/tests/regressiontests/forms/tests/media.py b/tests/regressiontests/forms/tests/media.py
index c492a1e..71e969e 100644
--- a/tests/regressiontests/forms/tests/media.py
+++ b/tests/regressiontests/forms/tests/media.py
@@ -455,6 +455,43 @@ class Media:
 <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
 <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
 
+    def test_inline_media(self):
+        ## Inline JavaScript and CSS
+        class MyWidget(TextInput):
+            class Media:
+                css = {'all': (Media.Inline('.mywidget { display: none; }'),)}
+                js = (Media.Inline('init_mywidget();'),)
+
+        w = MyWidget()
+        self.assertEqual('<style type="text/css" media="all">.mywidget { display: none; }</style>', str(w.media['css']))
+        self.assertEqual('<script type="text/javascript">init_mywidget();</script>', str(w.media['js']))
+
+    def test_inline_media_property(self):
+        ## Inline JavaScript and CSS as a media property
+        class MyWidget(TextInput):
+            def _media(self):
+                return Media(css={'all': (Media.Inline('.mywidget { display: none; }'),)},
+                             js=(Media.Inline('init_mywidget();'),))
+            media = property(_media)
+
+        w = MyWidget()
+        self.assertEqual('<style type="text/css" media="all">.mywidget { display: none; }</style>', str(w.media['css']))
+        self.assertEqual('<script type="text/javascript">init_mywidget();</script>', str(w.media['js']))
+
+    def test_inline_media_mutiple(self):
+        ## Multiple instances of inline media should only be rendered once
+        class MyWidget(TextInput):
+            class Media:
+                css = {'all': (Media.Inline('.mywidget { display: none; }'),)}
+                js = (Media.Inline('init_mywidget();'),)
+
+        class MyForm(Form):
+            field1 = CharField(widget=MyWidget)
+            field2 = CharField(widget=MyWidget)
+
+        f = MyForm()
+        self.assertEqual("""<style type="text/css" media="all">.mywidget { display: none; }</style>
+<script type="text/javascript">init_mywidget();</script>""", str(f.media))
 
 @override_settings(
     STATIC_URL='http://media.example.com/static/',
-- 
1.7.10

