Installation
-
Install
django_componentsinto your environment: -
Load
django_componentsinto Django by adding it intoINSTALLED_APPSin in your settings file: -
BASE_DIRsetting is required. Ensure that it is defined: -
Optional. Set
COMPONENTS.dirsand/orCOMPONENTS.app_dirsso django_components knows where to find component HTML, JS and CSS files:If
COMPONENTS.dirsis omitted, django-components will by default look for a top-level/componentsdirectory,{BASE_DIR}/components.from django_components import ComponentsSettings COMPONENTS = ComponentsSettings( dirs=[ ..., Path(BASE_DIR) / "components", ], )In addition to
COMPONENTS.dirs, django_components will also load components from app-level directories, such asmy-app/components/. The directories within apps are configured withCOMPONENTS.app_dirs, and the default is[app]/components.Note
The input to
COMPONENTS.dirsis the same as forSTATICFILES_DIRS, and the paths must be full paths. See Django docs. -
Next, modify
TEMPLATESsection of settings.py as follows:- Remove
'APP_DIRS': True,- NOTE: Instead of
APP_DIRS: True, we will usedjango.template.loaders.app_directories.Loader, which has the same effect.
- NOTE: Instead of
- Add
loaderstoOPTIONSlist and set it to following value:
This allows Django to load component HTML files as Django templates.
TEMPLATES = [ { ..., 'OPTIONS': { 'loaders':[( 'django.template.loaders.cached.Loader', [ # Default Django loader 'django.template.loaders.filesystem.Loader', # Including this is the same as APP_DIRS=True 'django.template.loaders.app_directories.Loader', # Components loader 'django_components.template_loader.Loader', ] )], }, }, ] - Remove
Adding support for JS and CSS¤
If you want to use JS or CSS with components, you will need to:
-
Add
"django_components.finders.ComponentsFileSystemFinder"toSTATICFILES_FINDERSin your settings file.This allows Django to serve component JS and CSS as static files.
-
Add
ComponentDependencyMiddlewaretoMIDDLEWAREsetting.The middleware searches the outgoing HTML for all components that were rendered to generate the HTML, and adds the JS and CSS associated with those components.
Read more in Rendering JS/CSS dependencies.
-
Add django-component's URL paths to your
urlpatterns: -
Optional. If you want to change where the JS and CSS is rendered, use
{% component_js_dependencies %}and{% component_css_dependencies %}.By default, the JS
<script>and CSS<link>tags are automatically inserted into the HTML (See JS and CSS output locations). -
Optional. By default, components' JS and CSS files are cached in memory.
If you want to change the cache backend, set the
COMPONENTS.cachesetting.Read more in Caching.
Optional¤
Builtin template tags¤
To avoid loading the app in each template using {% load component_tags %}, you can add the tag as a 'builtin' in settings.py
TEMPLATES = [
{
...,
'OPTIONS': {
'builtins': [
'django_components.templatetags.component_tags',
]
},
},
]
Now you're all set! Read on to find out how to build your first component.