Django JS Asset
django-js-asset (current version 3.1.2) provides a `JS` object to insert script tags with additional HTML attributes into Django's `forms.Media` definitions, addressing a limitation in older Django versions. It also extends `forms.Media` to support `CSS` and `JSON` objects, allowing for more flexible asset management. The library is actively maintained and releases align with Django's compatibility requirements, supporting Django 4.2 and newer versions.
Warnings
- gotcha Django 5.2+ introduces its own `Script` object for `forms.Media` with similar functionality. While `django-js-asset` offers a 'slightly different API' and extended features (like CSS/JSON objects and importmap support), users upgrading to Django 5.2 should be aware of the native option and choose the library that best fits their needs.
- deprecated The importmap support provided by `django-js-asset` is explicitly labeled as 'extremely experimental' and browser support for multiple importmaps is not generally available or standardized. Relying heavily on this feature in production is cautioned.
- gotcha When using the experimental importmap feature, if you add `importmap` to `forms.Media(js=[...])` and also include `{{ importmap }}` directly in your base templates (e.g., for Django admin), the importmap definition might be duplicated in the rendered HTML.
- gotcha The `static()` function's implementation can vary between Django versions, especially concerning `django.contrib.staticfiles`. `django-js-asset` provides its own `js_asset.static` helper to ensure correct static file URL resolution across supported Django versions.
Install
-
pip install django-js-asset
Imports
- JS
from js_asset import JS
- CSS
from js_asset import CSS
- JSON
from js_asset import JSON
Quickstart
from django import forms
from js_asset import JS, CSS, JSON
# Example form demonstrating usage of JS, CSS, and JSON objects in Media
class MyWidget(forms.TextInput):
class Media:
js = [
# Embed JSON data directly into a script tag
JSON({"setting": "value", "number": 123}, id="my-widget-config"),
# Include a JavaScript module with custom attributes
JS("my_app/js/script.js", {"type": "module", "data-priority": "high"}),
]
css = {
"all": [
# Include an external stylesheet
CSS("my_app/css/style.css"),
# Include inline CSS directly
CSS("p { color: blue; }", inline=True),
]
}
class MyForm(forms.Form):
my_field = forms.CharField(widget=MyWidget)
# In a Django template, you would render the media like this:
# {{ form.media }}