django-components 0.51__tar.gz → 0.60__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {django_components-0.51 → django_components-0.60}/PKG-INFO +69 -5
  2. {django_components-0.51 → django_components-0.60}/README.md +68 -4
  3. {django_components-0.51 → django_components-0.60}/django_components/__init__.py +7 -10
  4. {django_components-0.51 → django_components-0.60}/django_components/component.py +111 -13
  5. django_components-0.60/django_components/logger.py +3 -0
  6. django_components-0.60/django_components/template_loader.py +85 -0
  7. {django_components-0.51 → django_components-0.60}/django_components/templatetags/component_tags.py +24 -13
  8. {django_components-0.51 → django_components-0.60}/django_components/types.py +3 -3
  9. {django_components-0.51 → django_components-0.60}/django_components.egg-info/PKG-INFO +69 -5
  10. {django_components-0.51 → django_components-0.60}/django_components.egg-info/SOURCES.txt +1 -0
  11. {django_components-0.51 → django_components-0.60}/pyproject.toml +7 -0
  12. {django_components-0.51 → django_components-0.60}/setup.py +4 -1
  13. {django_components-0.51 → django_components-0.60}/tests/test_autodiscover.py +30 -9
  14. {django_components-0.51 → django_components-0.60}/tests/test_component.py +34 -0
  15. {django_components-0.51 → django_components-0.60}/tests/test_context.py +11 -3
  16. {django_components-0.51 → django_components-0.60}/tests/test_templatetags.py +2 -2
  17. django_components-0.51/django_components/template_loader.py +0 -35
  18. {django_components-0.51 → django_components-0.60}/LICENSE +0 -0
  19. {django_components-0.51 → django_components-0.60}/django_components/app_settings.py +0 -0
  20. {django_components-0.51 → django_components-0.60}/django_components/apps.py +0 -0
  21. {django_components-0.51 → django_components-0.60}/django_components/component_registry.py +0 -0
  22. {django_components-0.51 → django_components-0.60}/django_components/management/__init__.py +0 -0
  23. {django_components-0.51 → django_components-0.60}/django_components/management/commands/__init__.py +0 -0
  24. {django_components-0.51 → django_components-0.60}/django_components/management/commands/startcomponent.py +0 -0
  25. {django_components-0.51 → django_components-0.60}/django_components/management/commands/upgradecomponent.py +0 -0
  26. {django_components-0.51 → django_components-0.60}/django_components/middleware.py +0 -0
  27. {django_components-0.51 → django_components-0.60}/django_components/safer_staticfiles/__init__.py +0 -0
  28. {django_components-0.51 → django_components-0.60}/django_components/safer_staticfiles/apps.py +0 -0
  29. {django_components-0.51 → django_components-0.60}/django_components/templatetags/__init__.py +0 -0
  30. {django_components-0.51 → django_components-0.60}/django_components.egg-info/dependency_links.txt +0 -0
  31. {django_components-0.51 → django_components-0.60}/django_components.egg-info/requires.txt +0 -0
  32. {django_components-0.51 → django_components-0.60}/django_components.egg-info/top_level.txt +0 -0
  33. {django_components-0.51 → django_components-0.60}/setup.cfg +0 -0
  34. {django_components-0.51 → django_components-0.60}/tests/components/__init__.py +0 -0
  35. {django_components-0.51 → django_components-0.60}/tests/components/single_file.py +0 -0
  36. {django_components-0.51 → django_components-0.60}/tests/components/urls.py +0 -0
  37. {django_components-0.51 → django_components-0.60}/tests/test_component_as_view.py +0 -0
  38. {django_components-0.51 → django_components-0.60}/tests/test_dependency_rendering.py +0 -0
  39. {django_components-0.51 → django_components-0.60}/tests/test_registry.py +0 -0
  40. {django_components-0.51 → django_components-0.60}/tests/test_settings.py +0 -0
  41. {django_components-0.51 → django_components-0.60}/tests/test_startcomponent_command.py +0 -0
  42. {django_components-0.51 → django_components-0.60}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.51
3
+ Version: 0.60
4
4
  Summary: A way to create simple reusable template components in Django.
5
5
  Home-page: https://github.com/EmilStenstrom/django-components/
6
6
  Author: Emil Stenström
@@ -225,7 +225,7 @@ from django_components import component
225
225
  class Calendar(component.Component):
226
226
  # Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
227
227
  # you can override def get_template_name() instead of specifying the below variable.
228
- template_name = "calendar/calendar.html"
228
+ template_name = "calendar.html"
229
229
 
230
230
  # This component takes one parameter, a date string to show in the template
231
231
  def get_context_data(self, date):
@@ -234,8 +234,8 @@ class Calendar(component.Component):
234
234
  }
235
235
 
236
236
  class Media:
237
- css = "calendar/style.css"
238
- js = "calendar/script.js"
237
+ css = "style.css"
238
+ js = "script.js"
239
239
  ```
240
240
 
241
241
  And voilá!! We've created our first component.
@@ -710,6 +710,36 @@ COMPONENTS = {
710
710
  }
711
711
  ```
712
712
 
713
+ ## Logging and debugging
714
+
715
+ Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
716
+
717
+ To configure logging for Django components, set the `django_components` logger in `LOGGING` in `settings.py` (below).
718
+
719
+ Also see the [`settings.py` file in sampleproject](./sampleproject/sampleproject/settings.py) for a real-life example.
720
+
721
+ ```py
722
+ import logging
723
+ import sys
724
+
725
+ LOGGING = {
726
+ 'version': 1,
727
+ 'disable_existing_loggers': False,
728
+ "handlers": {
729
+ "console": {
730
+ 'class': 'logging.StreamHandler',
731
+ 'stream': sys.stdout,
732
+ },
733
+ },
734
+ "loggers": {
735
+ "django_components": {
736
+ "level": logging.DEBUG,
737
+ "handlers": ["console"],
738
+ },
739
+ },
740
+ }
741
+ ```
742
+
713
743
  ## Management Command
714
744
 
715
745
  You can use the built-in management command `startcomponent` to create a django component. The command accepts the following arguments and options:
@@ -790,7 +820,10 @@ One of our goals with `django-components` is to make it easy to share components
790
820
 
791
821
  - [django-htmx-components](https://github.com/iwanalabs/django-htmx-components): A set of components for use with [htmx](https://htmx.org/). Try out the [live demo](https://dhc.iwanalabs.com/).
792
822
 
793
- ## Install locally and run the tests
823
+
824
+ ## Running django-components project locally
825
+
826
+ ### Install locally and run the tests
794
827
 
795
828
  Start by forking the project by clicking the **Fork button** up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
796
829
 
@@ -823,3 +856,34 @@ pyenv install -s 3.12
823
856
  pyenv local 3.6 3.7 3.8 3.9 3.10 3.11 3.12
824
857
  tox -p
825
858
  ```
859
+
860
+ ### Developing against live Django app
861
+
862
+ How do you check that your changes to django-components project will work in an actual Django project?
863
+
864
+ Use the [sampleproject](./sampleproject/) demo project to validate the changes:
865
+
866
+ 1. Navigate to [sampleproject](./sampleproject/) directory:
867
+ ```sh
868
+ cd sampleproject
869
+ ```
870
+
871
+ 2. Install dependencies from the [requirements.txt](./sampleproject/requirements.txt) file:
872
+ ```sh
873
+ pip install -r requirements.txt
874
+ ```
875
+
876
+ 3. Link to your local version of django-components:
877
+ ```sh
878
+ pip install -e ..
879
+ ```
880
+ NOTE: The path (in this case `..`) must point to the directory that has the `setup.py` file.
881
+
882
+ 4. Start Django server
883
+ ```sh
884
+ python manage.py runserver
885
+ ```
886
+
887
+ Once the server is up, it should be available at <http://127.0.0.1:8000>.
888
+
889
+ To display individual components, add them to the `urls.py`, like in the case of <http://127.0.0.1:8000/greeting>
@@ -196,7 +196,7 @@ from django_components import component
196
196
  class Calendar(component.Component):
197
197
  # Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
198
198
  # you can override def get_template_name() instead of specifying the below variable.
199
- template_name = "calendar/calendar.html"
199
+ template_name = "calendar.html"
200
200
 
201
201
  # This component takes one parameter, a date string to show in the template
202
202
  def get_context_data(self, date):
@@ -205,8 +205,8 @@ class Calendar(component.Component):
205
205
  }
206
206
 
207
207
  class Media:
208
- css = "calendar/style.css"
209
- js = "calendar/script.js"
208
+ css = "style.css"
209
+ js = "script.js"
210
210
  ```
211
211
 
212
212
  And voilá!! We've created our first component.
@@ -681,6 +681,36 @@ COMPONENTS = {
681
681
  }
682
682
  ```
683
683
 
684
+ ## Logging and debugging
685
+
686
+ Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
687
+
688
+ To configure logging for Django components, set the `django_components` logger in `LOGGING` in `settings.py` (below).
689
+
690
+ Also see the [`settings.py` file in sampleproject](./sampleproject/sampleproject/settings.py) for a real-life example.
691
+
692
+ ```py
693
+ import logging
694
+ import sys
695
+
696
+ LOGGING = {
697
+ 'version': 1,
698
+ 'disable_existing_loggers': False,
699
+ "handlers": {
700
+ "console": {
701
+ 'class': 'logging.StreamHandler',
702
+ 'stream': sys.stdout,
703
+ },
704
+ },
705
+ "loggers": {
706
+ "django_components": {
707
+ "level": logging.DEBUG,
708
+ "handlers": ["console"],
709
+ },
710
+ },
711
+ }
712
+ ```
713
+
684
714
  ## Management Command
685
715
 
686
716
  You can use the built-in management command `startcomponent` to create a django component. The command accepts the following arguments and options:
@@ -761,7 +791,10 @@ One of our goals with `django-components` is to make it easy to share components
761
791
 
762
792
  - [django-htmx-components](https://github.com/iwanalabs/django-htmx-components): A set of components for use with [htmx](https://htmx.org/). Try out the [live demo](https://dhc.iwanalabs.com/).
763
793
 
764
- ## Install locally and run the tests
794
+
795
+ ## Running django-components project locally
796
+
797
+ ### Install locally and run the tests
765
798
 
766
799
  Start by forking the project by clicking the **Fork button** up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
767
800
 
@@ -794,3 +827,34 @@ pyenv install -s 3.12
794
827
  pyenv local 3.6 3.7 3.8 3.9 3.10 3.11 3.12
795
828
  tox -p
796
829
  ```
830
+
831
+ ### Developing against live Django app
832
+
833
+ How do you check that your changes to django-components project will work in an actual Django project?
834
+
835
+ Use the [sampleproject](./sampleproject/) demo project to validate the changes:
836
+
837
+ 1. Navigate to [sampleproject](./sampleproject/) directory:
838
+ ```sh
839
+ cd sampleproject
840
+ ```
841
+
842
+ 2. Install dependencies from the [requirements.txt](./sampleproject/requirements.txt) file:
843
+ ```sh
844
+ pip install -r requirements.txt
845
+ ```
846
+
847
+ 3. Link to your local version of django-components:
848
+ ```sh
849
+ pip install -e ..
850
+ ```
851
+ NOTE: The path (in this case `..`) must point to the directory that has the `setup.py` file.
852
+
853
+ 4. Start Django server
854
+ ```sh
855
+ python manage.py runserver
856
+ ```
857
+
858
+ Once the server is up, it should be available at <http://127.0.0.1:8000>.
859
+
860
+ To display individual components, add them to the `urls.py`, like in the case of <http://127.0.0.1:8000/greeting>
@@ -1,14 +1,12 @@
1
- import glob
2
1
  import importlib
3
2
  import importlib.util
4
3
  import sys
5
4
  from pathlib import Path
6
5
 
7
6
  import django
8
- from django.template.engine import Engine
9
7
  from django.utils.module_loading import autodiscover_modules
10
8
 
11
- from django_components.template_loader import Loader
9
+ from django_components.utils.autodiscover import search
12
10
 
13
11
  if django.VERSION < (3, 2):
14
12
  default_app_config = "django_components.apps.ComponentsConfig"
@@ -22,12 +20,9 @@ def autodiscover():
22
20
  autodiscover_modules("components")
23
21
 
24
22
  # Autodetect a <component>.py file in a components dir
25
- current_engine = Engine.get_default()
26
- loader = Loader(current_engine)
27
- dirs = loader.get_dirs()
28
- for directory in dirs:
29
- for path in glob.iglob(str(directory / "**/*.py"), recursive=True):
30
- import_file(path)
23
+ component_filepaths = search(search_glob="**/*.py")
24
+ for path in component_filepaths:
25
+ import_file(path)
31
26
 
32
27
  for path in app_settings.LIBRARIES:
33
28
  importlib.import_module(path)
@@ -37,6 +32,8 @@ def import_file(path):
37
32
  MODULE_PATH = path
38
33
  MODULE_NAME = Path(path).stem
39
34
  spec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)
35
+ if spec is None:
36
+ raise ValueError(f"Cannot import file '{path}' - invalid path")
40
37
  module = importlib.util.module_from_spec(spec)
41
38
  sys.modules[spec.name] = module
42
- spec.loader.exec_module(module)
39
+ spec.loader.exec_module(module) # type: ignore
@@ -1,7 +1,8 @@
1
1
  import difflib
2
2
  import inspect
3
+ import os
3
4
  from collections import ChainMap
4
- from typing import Any, ClassVar, Dict, Iterable, Optional, Set, Tuple, Union
5
+ from typing import Any, ClassVar, Dict, Iterable, List, Optional, Set, Tuple, Union
5
6
 
6
7
  from django.core.exceptions import ImproperlyConfigured
7
8
  from django.forms.widgets import Media, MediaDefiningClass
@@ -25,6 +26,7 @@ from django_components.component_registry import ( # NOQA
25
26
  register,
26
27
  registry,
27
28
  )
29
+ from django_components.logger import logger
28
30
  from django_components.templatetags.component_tags import (
29
31
  FILLED_SLOTS_CONTENT_CONTEXT_KEY,
30
32
  DefaultFillContent,
@@ -35,12 +37,13 @@ from django_components.templatetags.component_tags import (
35
37
  SlotName,
36
38
  SlotNode,
37
39
  )
40
+ from django_components.utils.autodiscover import search
38
41
 
39
42
 
40
43
  class SimplifiedInterfaceMediaDefiningClass(MediaDefiningClass):
41
44
  def __new__(mcs, name, bases, attrs):
42
45
  if "Media" in attrs:
43
- media = attrs["Media"]
46
+ media: Component.Media = attrs["Media"]
44
47
 
45
48
  # Allow: class Media: css = "style.css"
46
49
  if hasattr(media, "css") and isinstance(media.css, str):
@@ -54,33 +57,128 @@ class SimplifiedInterfaceMediaDefiningClass(MediaDefiningClass):
54
57
  if hasattr(media, "css") and isinstance(media.css, dict):
55
58
  for media_type, path_list in media.css.items():
56
59
  if isinstance(path_list, str):
57
- media.css[media_type] = [path_list]
60
+ media.css[media_type] = [path_list] # type: ignore
58
61
 
59
62
  # Allow: class Media: js = "script.js"
60
63
  if hasattr(media, "js") and isinstance(media.js, str):
61
64
  media.js = [media.js]
62
65
 
66
+ _resolve_component_relative_files(attrs)
67
+
63
68
  return super().__new__(mcs, name, bases, attrs)
64
69
 
65
70
 
71
+ def _resolve_component_relative_files(attrs: dict):
72
+ """
73
+ Check if component's HTML, JS and CSS files refer to files in the same directory
74
+ as the component class. If so, modify the attributes so the class Django's rendering
75
+ will pick up these files correctly.
76
+ """
77
+ module_name = attrs["__module__"]
78
+
79
+ # Prepare all possible directories we need to check when searching for
80
+ # component's template and media files
81
+ components_dirs = search()
82
+
83
+ # Get the directory where the component class is defined
84
+ try:
85
+ comp_dir_abs, comp_dir_rel = _get_dir_path_from_component_module_path(module_name, components_dirs)
86
+ except RuntimeError:
87
+ # If no dir was found, we assume that the path is NOT relative to the component dir
88
+ logger.debug(
89
+ f"No component directory found for component '{module_name}'."
90
+ " If this component defines HTML, JS or CSS templates relatively to the component file,"
91
+ " then check that the component's directory is accessible from one of the paths"
92
+ " specified in the Django's 'STATICFILES_DIRS' settings."
93
+ )
94
+ return
95
+
96
+ # Check if filepath refers to a file that's in the same directory as the component class.
97
+ # If yes, modify the path to refer to the relative file.
98
+ # If not, don't modify anything.
99
+ def resolve_file(filepath: str):
100
+ maybe_resolved_filepath = os.path.join(comp_dir_abs, filepath)
101
+ component_import_filepath = os.path.join(comp_dir_rel, filepath)
102
+
103
+ if os.path.isfile(maybe_resolved_filepath):
104
+ logger.debug(
105
+ f"Interpreting template '{filepath}' of component '{module_name}' relatively to component file"
106
+ )
107
+ return component_import_filepath
108
+
109
+ logger.debug(
110
+ f"Interpreting template '{filepath}' of component '{module_name}' relatively to components directory"
111
+ )
112
+ return filepath
113
+
114
+ # Check if template name is a local file or not
115
+ if "template_name" in attrs and attrs["template_name"]:
116
+ attrs["template_name"] = resolve_file(attrs["template_name"])
117
+
118
+ if "Media" in attrs:
119
+ media = attrs["Media"]
120
+
121
+ # Now check the same for CSS files
122
+ if hasattr(media, "css") and isinstance(media.css, dict):
123
+ for media_type, path_list in media.css.items():
124
+ media.css[media_type] = [resolve_file(filepath) for filepath in path_list]
125
+
126
+ # And JS
127
+ if hasattr(media, "js") and isinstance(media.js, list):
128
+ media.js = [resolve_file(filepath) for filepath in media.js]
129
+
130
+
131
+ def _get_dir_path_from_component_module_path(component_module_path: str, candidate_dirs: List[str]):
132
+ # Transform python module notation "pkg.module.name" to file path "pkg/module/name"
133
+ # Thus, we should get file path relative to Django project root
134
+ comp_path = os.sep.join(component_module_path.split("."))
135
+ comp_dir_path = os.path.dirname(comp_path)
136
+
137
+ # NOTE: We assume that Django project root == current working directory!
138
+ cwd = os.getcwd()
139
+ comp_dir_path_abs = os.path.join(cwd, comp_dir_path)
140
+
141
+ # From all dirs defined in settings.STATICFILES_DIRS, find one that's the parent
142
+ # to the component file.
143
+ root_dir_abs = None
144
+ for candidate_dir in candidate_dirs:
145
+ candidate_dir_abs = os.path.abspath(candidate_dir)
146
+ if comp_dir_path_abs.startswith(candidate_dir_abs):
147
+ root_dir_abs = candidate_dir_abs
148
+ break
149
+
150
+ if root_dir_abs is None:
151
+ raise RuntimeError(
152
+ f"Failed to resolve template directory for component '{component_module_path}'",
153
+ )
154
+
155
+ # Derive the path from matched STATICFILES_DIRS to the dir where the current component file is.
156
+ comp_dir_path_rel = os.path.relpath(comp_dir_path_abs, candidate_dir_abs)
157
+
158
+ # Return both absolute and relative paths:
159
+ # - Absolute path is used to check if the file exists
160
+ # - Relative path is used for defining the import on the component class
161
+ return comp_dir_path_abs, comp_dir_path_rel
162
+
163
+
66
164
  class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
67
165
  # Either template_name or template must be set on subclass OR subclass must implement get_template() with
68
166
  # non-null return.
69
167
  template_name: ClassVar[Optional[str]] = None
70
- template: ClassVar[Optional[str]] = None
71
- js: ClassVar[Optional[str]] = None
72
- css: ClassVar[Optional[str]] = None
168
+ template: Optional[str] = None
169
+ js: Optional[str] = None
170
+ css: Optional[str] = None
73
171
  media: Media
74
172
 
75
173
  class Media:
76
- css = {}
77
- js = []
174
+ css: Optional[Union[str, List[str], Dict[str, str], Dict[str, List[str]]]] = None
175
+ js: Optional[Union[str, List[str]]] = None
78
176
 
79
177
  def __init__(
80
178
  self,
81
179
  registered_name: Optional[str] = None,
82
180
  outer_context: Optional[Context] = None,
83
- fill_content: Union[DefaultFillContent, Iterable[NamedFillContent]] = (),
181
+ fill_content: Union[DefaultFillContent, Iterable[NamedFillContent]] = (), # type: ignore
84
182
  ):
85
183
  self.registered_name: Optional[str] = registered_name
86
184
  self.outer_context: Context = outer_context or Context()
@@ -142,7 +240,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
142
240
  self,
143
241
  context_data: Dict[str, Any],
144
242
  slots_data: Optional[Dict[SlotName, str]] = None,
145
- escape_slots_content: Optional[bool] = True,
243
+ escape_slots_content: bool = True,
146
244
  ) -> str:
147
245
  context = Context(context_data)
148
246
  template = self.get_template(context)
@@ -160,7 +258,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
160
258
  self,
161
259
  context_data: Dict[str, Any],
162
260
  slots_data: Optional[Dict[SlotName, str]] = None,
163
- escape_slots_content: Optional[bool] = True,
261
+ escape_slots_content: bool = True,
164
262
  *args,
165
263
  **kwargs,
166
264
  ):
@@ -173,7 +271,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
173
271
  def _fill_slots(
174
272
  self,
175
273
  slots_data: Dict[SlotName, str],
176
- escape_content: bool,
274
+ escape_content: bool = True,
177
275
  ):
178
276
  """Fill component slots outside of template rendering."""
179
277
  self.fill_content = [
@@ -195,7 +293,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
195
293
  named_fills_content = {}
196
294
  else:
197
295
  default_fill_content = None
198
- named_fills_content = {name: (nodelist, alias) for name, nodelist, alias in self.fill_content}
296
+ named_fills_content = {name: (nodelist, alias) for name, nodelist, alias in list(self.fill_content)}
199
297
 
200
298
  # If value is `None`, then slot is unfilled.
201
299
  slot_name2fill_content: Dict[SlotName, Optional[FillContent]] = {}
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("django_components")
@@ -0,0 +1,85 @@
1
+ """
2
+ Template loader that loads templates from each Django app's "components" directory.
3
+ """
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Set
8
+
9
+ from django.apps import apps
10
+ from django.conf import settings
11
+ from django.template.loaders.filesystem import Loader as FilesystemLoader
12
+
13
+ from django_components.logger import logger
14
+
15
+
16
+ # Same as `Path.is_relative_to`, defined as standalone function because `Path.is_relative_to`
17
+ # is marked for deprecation.
18
+ def path_is_relative_to(child_path: str, parent_path: str):
19
+ # If the relative path doesn't start with `..`, then child is descendant of parent
20
+ # See https://stackoverflow.com/a/7288073/9788634
21
+ rel_path = os.path.relpath(child_path, parent_path)
22
+ return not rel_path.startswith("..")
23
+
24
+
25
+ class Loader(FilesystemLoader):
26
+ def get_dirs(self):
27
+ # Allow to configure from settings which dirs should be checked for components
28
+ if hasattr(settings, "STATICFILES_DIRS") and len(settings.STATICFILES_DIRS):
29
+ component_dirs = settings.STATICFILES_DIRS
30
+ else:
31
+ component_dirs = ["components"]
32
+
33
+ logger.debug(
34
+ "Template loader will search for valid template dirs from following options:\n"
35
+ + "\n".join([f" - {str(d)}" for d in component_dirs])
36
+ )
37
+
38
+ directories: Set[Path] = set()
39
+ for component_dir in component_dirs:
40
+ curr_directories: Set[Path] = set()
41
+
42
+ # For each dir in `settings.STATICFILES_DIRS`, we go over all Django apps
43
+ # and, for each app, check if the STATICFILES_DIRS dir is within that app dir.
44
+ # If so, we add the dir as a valid source.
45
+ # The for loop is based on Django's `get_app_template_dirs`.
46
+ for app_config in apps.get_app_configs():
47
+ if not app_config.path:
48
+ continue
49
+ if not Path(component_dir).is_dir():
50
+ continue
51
+
52
+ if path_is_relative_to(component_dir, app_config.path):
53
+ curr_directories.add(Path(component_dir).resolve())
54
+
55
+ if hasattr(settings, "BASE_DIR"):
56
+ path = (Path(settings.BASE_DIR) / component_dir).resolve()
57
+ if path.is_dir():
58
+ curr_directories.add(path)
59
+
60
+ # Add the directory that holds the settings file
61
+ if settings.SETTINGS_MODULE:
62
+ module_parts = settings.SETTINGS_MODULE.split(".")
63
+ module_path = Path(*module_parts)
64
+
65
+ # - If len() == 2, then path to settings file is <app_name>/<settings_file>.py
66
+ # - If len() > 2, then we assume that settings file is in a settings directory,
67
+ # e.g. <app_name>/settings/<settings_file>.py
68
+ if len(module_parts) > 2:
69
+ module_path = Path(*module_parts[:-1])
70
+
71
+ # Get the paths for the nested settings dir like `<app_name>/settings`,
72
+ # or for non-nested dir like `<app_name>`
73
+ #
74
+ # NOTE: Use list() for < Python 3.9
75
+ for parent in list(module_path.parents)[:2]:
76
+ path = (parent / component_dir).resolve()
77
+ if path.is_dir():
78
+ curr_directories.add(path)
79
+
80
+ directories.update(curr_directories)
81
+
82
+ logger.debug(
83
+ "Template loader matched following template dirs:\n" + "\n".join([f" - {str(d)}" for d in directories])
84
+ )
85
+ return list(directories)
@@ -1,5 +1,5 @@
1
1
  import sys
2
- from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Type, Union
2
+ from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union
3
3
 
4
4
  if sys.version_info[:2] < (3, 9):
5
5
  from typing import ChainMap
@@ -194,7 +194,7 @@ class SlotNode(Node, TemplateAwareNodeMixin):
194
194
 
195
195
  extra_context = {}
196
196
  try:
197
- slot_fill_content: Optional[FillContent] = filled_slots_map[(self.name, self.template)]
197
+ slot_fill_content: FillContent = filled_slots_map[(self.name, self.template)]
198
198
  except KeyError:
199
199
  if self.is_required:
200
200
  raise TemplateSyntaxError(
@@ -375,16 +375,17 @@ class ComponentNode(Node):
375
375
  # Note that outer component context is used to resolve variables in
376
376
  # fill tag.
377
377
  resolved_name = fill_node.name_fexp.resolve(context)
378
+ resolved_alias: Optional[str]
378
379
  if fill_node.alias_fexp:
379
- resolved_alias: str = fill_node.alias_fexp.resolve(context)
380
- if not resolved_alias.isidentifier():
380
+ resolved_alias = fill_node.alias_fexp.resolve(context)
381
+ if resolved_alias and not resolved_alias.isidentifier():
381
382
  raise TemplateSyntaxError(
382
383
  f"Fill tag alias '{fill_node.alias_fexp.var}' in component "
383
384
  f"{resolved_component_name} does not resolve to "
384
385
  f"a valid Python identifier. Got: '{resolved_alias}'."
385
386
  )
386
387
  else:
387
- resolved_alias: None = None
388
+ resolved_alias = None
388
389
  fill_content.append((resolved_name, fill_node.nodelist, resolved_alias))
389
390
 
390
391
  component: Component = component_cls(
@@ -426,14 +427,15 @@ def do_component(parser, token):
426
427
  component_name, context_args, context_kwargs = parse_component_with_args(parser, bits, "component")
427
428
  body: NodeList = parser.parse(parse_until=["endcomponent"])
428
429
  parser.delete_first_token()
429
- fill_nodes = ()
430
+ fill_nodes: Union[Iterable[NamedFillNode], ImplicitFillNode] = []
430
431
  if block_has_content(body):
431
432
  for parse_fn in (
432
433
  try_parse_as_default_fill,
433
434
  try_parse_as_named_fill_tag_set,
434
435
  ):
435
- fill_nodes = parse_fn(body)
436
- if fill_nodes:
436
+ curr_fill_nodes = parse_fn(body)
437
+ if curr_fill_nodes:
438
+ fill_nodes = curr_fill_nodes
437
439
  break
438
440
  else:
439
441
  raise TemplateSyntaxError(
@@ -457,7 +459,7 @@ def try_parse_as_named_fill_tag_set(
457
459
  nodelist: NodeList,
458
460
  ) -> Optional[Iterable[NamedFillNode]]:
459
461
  result = []
460
- seen_name_fexps = set()
462
+ seen_name_fexps: Set[FilterExpression] = set()
461
463
  for node in nodelist:
462
464
  if isinstance(node, NamedFillNode):
463
465
  if node.name_fexp in seen_name_fexps:
@@ -465,6 +467,7 @@ def try_parse_as_named_fill_tag_set(
465
467
  f"Multiple fill tags cannot target the same slot name: "
466
468
  f"Detected duplicate fill tag name '{node.name_fexp}'."
467
469
  )
470
+ seen_name_fexps.add(node.name_fexp)
468
471
  result.append(node)
469
472
  elif isinstance(node, CommentNode):
470
473
  pass
@@ -544,9 +547,13 @@ def do_if_filled_block(parser, token):
544
547
  bits = token.split_contents()
545
548
  starting_tag = bits[0]
546
549
  slot_name, is_positive = parse_if_filled_bits(bits)
547
- nodelist = parser.parse(("elif_filled", "else_filled", "endif_filled"))
550
+ nodelist: NodeList = parser.parse(("elif_filled", "else_filled", "endif_filled"))
548
551
  branches: List[_IfSlotFilledBranchNode] = [
549
- IfSlotFilledConditionBranchNode(slot_name=slot_name, nodelist=nodelist, is_positive=is_positive)
552
+ IfSlotFilledConditionBranchNode(
553
+ slot_name=slot_name, # type: ignore
554
+ nodelist=nodelist,
555
+ is_positive=is_positive,
556
+ )
550
557
  ]
551
558
 
552
559
  token = parser.next_token()
@@ -555,9 +562,13 @@ def do_if_filled_block(parser, token):
555
562
  while token.contents.startswith("elif_filled"):
556
563
  bits = token.split_contents()
557
564
  slot_name, is_positive = parse_if_filled_bits(bits)
558
- nodelist: NodeList = parser.parse(("elif_filled", "else_filled", "endif_filled"))
565
+ nodelist = parser.parse(("elif_filled", "else_filled", "endif_filled"))
559
566
  branches.append(
560
- IfSlotFilledConditionBranchNode(slot_name=slot_name, nodelist=nodelist, is_positive=is_positive)
567
+ IfSlotFilledConditionBranchNode(
568
+ slot_name=slot_name, # type: ignore
569
+ nodelist=nodelist,
570
+ is_positive=is_positive,
571
+ )
561
572
  )
562
573
 
563
574
  token = parser.next_token()
@@ -1,8 +1,8 @@
1
1
  try:
2
- from typing import Annotated
2
+ from typing import Annotated # type: ignore
3
3
  except ImportError:
4
4
 
5
- class Annotated:
5
+ class Annotated: # type: ignore
6
6
  def __init__(self, type_, *args, **kwargs):
7
7
  self.type_ = type_
8
8
  self.metadata = args, kwargs
@@ -13,7 +13,7 @@ except ImportError:
13
13
  def __getitem__(self, params):
14
14
  if not isinstance(params, tuple):
15
15
  params = (params,)
16
- return Annotated(self.type_, *params, **self.metadata[1])
16
+ return Annotated(self.type_, *params, **self.metadata[1]) # type: ignore
17
17
 
18
18
 
19
19
  css = Annotated[str, "css"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.51
3
+ Version: 0.60
4
4
  Summary: A way to create simple reusable template components in Django.
5
5
  Home-page: https://github.com/EmilStenstrom/django-components/
6
6
  Author: Emil Stenström
@@ -225,7 +225,7 @@ from django_components import component
225
225
  class Calendar(component.Component):
226
226
  # Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
227
227
  # you can override def get_template_name() instead of specifying the below variable.
228
- template_name = "calendar/calendar.html"
228
+ template_name = "calendar.html"
229
229
 
230
230
  # This component takes one parameter, a date string to show in the template
231
231
  def get_context_data(self, date):
@@ -234,8 +234,8 @@ class Calendar(component.Component):
234
234
  }
235
235
 
236
236
  class Media:
237
- css = "calendar/style.css"
238
- js = "calendar/script.js"
237
+ css = "style.css"
238
+ js = "script.js"
239
239
  ```
240
240
 
241
241
  And voilá!! We've created our first component.
@@ -710,6 +710,36 @@ COMPONENTS = {
710
710
  }
711
711
  ```
712
712
 
713
+ ## Logging and debugging
714
+
715
+ Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
716
+
717
+ To configure logging for Django components, set the `django_components` logger in `LOGGING` in `settings.py` (below).
718
+
719
+ Also see the [`settings.py` file in sampleproject](./sampleproject/sampleproject/settings.py) for a real-life example.
720
+
721
+ ```py
722
+ import logging
723
+ import sys
724
+
725
+ LOGGING = {
726
+ 'version': 1,
727
+ 'disable_existing_loggers': False,
728
+ "handlers": {
729
+ "console": {
730
+ 'class': 'logging.StreamHandler',
731
+ 'stream': sys.stdout,
732
+ },
733
+ },
734
+ "loggers": {
735
+ "django_components": {
736
+ "level": logging.DEBUG,
737
+ "handlers": ["console"],
738
+ },
739
+ },
740
+ }
741
+ ```
742
+
713
743
  ## Management Command
714
744
 
715
745
  You can use the built-in management command `startcomponent` to create a django component. The command accepts the following arguments and options:
@@ -790,7 +820,10 @@ One of our goals with `django-components` is to make it easy to share components
790
820
 
791
821
  - [django-htmx-components](https://github.com/iwanalabs/django-htmx-components): A set of components for use with [htmx](https://htmx.org/). Try out the [live demo](https://dhc.iwanalabs.com/).
792
822
 
793
- ## Install locally and run the tests
823
+
824
+ ## Running django-components project locally
825
+
826
+ ### Install locally and run the tests
794
827
 
795
828
  Start by forking the project by clicking the **Fork button** up in the right corner in the GitHub . This makes a copy of the repository in your own name. Now you can clone this repository locally and start adding features:
796
829
 
@@ -823,3 +856,34 @@ pyenv install -s 3.12
823
856
  pyenv local 3.6 3.7 3.8 3.9 3.10 3.11 3.12
824
857
  tox -p
825
858
  ```
859
+
860
+ ### Developing against live Django app
861
+
862
+ How do you check that your changes to django-components project will work in an actual Django project?
863
+
864
+ Use the [sampleproject](./sampleproject/) demo project to validate the changes:
865
+
866
+ 1. Navigate to [sampleproject](./sampleproject/) directory:
867
+ ```sh
868
+ cd sampleproject
869
+ ```
870
+
871
+ 2. Install dependencies from the [requirements.txt](./sampleproject/requirements.txt) file:
872
+ ```sh
873
+ pip install -r requirements.txt
874
+ ```
875
+
876
+ 3. Link to your local version of django-components:
877
+ ```sh
878
+ pip install -e ..
879
+ ```
880
+ NOTE: The path (in this case `..`) must point to the directory that has the `setup.py` file.
881
+
882
+ 4. Start Django server
883
+ ```sh
884
+ python manage.py runserver
885
+ ```
886
+
887
+ Once the server is up, it should be available at <http://127.0.0.1:8000>.
888
+
889
+ To display individual components, add them to the `urls.py`, like in the case of <http://127.0.0.1:8000/greeting>
@@ -7,6 +7,7 @@ django_components/app_settings.py
7
7
  django_components/apps.py
8
8
  django_components/component.py
9
9
  django_components/component_registry.py
10
+ django_components/logger.py
10
11
  django_components/middleware.py
11
12
  django_components/template_loader.py
12
13
  django_components/types.py
@@ -35,4 +35,11 @@ exclude = [
35
35
  '.env',
36
36
  '.venv',
37
37
  '.tox',
38
+ ]
39
+
40
+ [tool.mypy]
41
+ check_untyped_defs = true
42
+ ignore_missing_imports = true
43
+ exclude = [
44
+ 'test_structures'
38
45
  ]
@@ -3,11 +3,14 @@ import os
3
3
 
4
4
  from setuptools import find_packages, setup
5
5
 
6
- VERSION = "0.51"
6
+ VERSION = "0.60"
7
7
 
8
8
  setup(
9
9
  name="django_components",
10
10
  packages=find_packages(exclude=["tests"]),
11
+ package_data={
12
+ "django_components": ["py.typed"],
13
+ },
11
14
  version=VERSION,
12
15
  description="A way to create simple reusable template components in Django.",
13
16
  long_description=open(os.path.join(os.path.dirname(__file__), "README.md"), encoding="utf8").read(),
@@ -40,7 +40,14 @@ class TestLoaderSettingsModule(SimpleTestCase):
40
40
  current_engine = Engine.get_default()
41
41
  loader = Loader(current_engine)
42
42
  dirs = loader.get_dirs()
43
- self.assertEqual(dirs, [Path(__file__).parent.resolve() / "components"])
43
+ self.assertEqual(
44
+ sorted(dirs),
45
+ sorted(
46
+ [
47
+ Path(__file__).parent.resolve() / "components",
48
+ ]
49
+ ),
50
+ )
44
51
 
45
52
  def test_complex_settings_module(self):
46
53
  settings.SETTINGS_MODULE = "tests.test_structures.test_structure_1.config.settings" # noqa
@@ -49,8 +56,12 @@ class TestLoaderSettingsModule(SimpleTestCase):
49
56
  loader = Loader(current_engine)
50
57
  dirs = loader.get_dirs()
51
58
  self.assertEqual(
52
- dirs,
53
- [Path(__file__).parent.resolve() / "test_structures" / "test_structure_1" / "components"],
59
+ sorted(dirs),
60
+ sorted(
61
+ [
62
+ Path(__file__).parent.resolve() / "test_structures" / "test_structure_1" / "components",
63
+ ]
64
+ ),
54
65
  )
55
66
 
56
67
  def test_complex_settings_module_2(self):
@@ -60,8 +71,16 @@ class TestLoaderSettingsModule(SimpleTestCase):
60
71
  loader = Loader(current_engine)
61
72
  dirs = loader.get_dirs()
62
73
  self.assertEqual(
63
- dirs,
64
- [Path(__file__).parent.resolve() / "test_structures" / "test_structure_2" / "project" / "components"],
74
+ sorted(dirs),
75
+ sorted(
76
+ [
77
+ Path(__file__).parent.resolve()
78
+ / "test_structures"
79
+ / "test_structure_2"
80
+ / "project"
81
+ / "components",
82
+ ]
83
+ ),
65
84
  )
66
85
 
67
86
  def test_complex_settings_module_3(self):
@@ -71,8 +90,8 @@ class TestLoaderSettingsModule(SimpleTestCase):
71
90
  loader = Loader(current_engine)
72
91
  dirs = loader.get_dirs()
73
92
  expected = [
74
- (Path(__file__).parent.resolve() / "test_structures" / "test_structure_3" / "components"),
75
- (Path(__file__).parent.resolve() / "test_structures" / "test_structure_3" / "project" / "components"),
93
+ Path(__file__).parent.resolve() / "test_structures" / "test_structure_3" / "components",
94
+ Path(__file__).parent.resolve() / "test_structures" / "test_structure_3" / "project" / "components",
76
95
  ]
77
96
  self.assertEqual(
78
97
  sorted(dirs),
@@ -93,5 +112,7 @@ class TestBaseDir(SimpleTestCase):
93
112
  current_engine = Engine.get_default()
94
113
  loader = Loader(current_engine)
95
114
  dirs = loader.get_dirs()
96
- expected = [Path(__file__).parent.resolve() / "test_structures" / "test_structure_1" / "components"]
97
- self.assertEqual(dirs, expected)
115
+ expected = [
116
+ Path(__file__).parent.resolve() / "test_structures" / "test_structure_1" / "components",
117
+ ]
118
+ self.assertEqual(sorted(dirs), sorted(expected))
@@ -1,7 +1,9 @@
1
+ from pathlib import Path
1
2
  from textwrap import dedent
2
3
 
3
4
  from django.core.exceptions import ImproperlyConfigured
4
5
  from django.template import Context, Template
6
+ from django.test import override_settings
5
7
 
6
8
  # isort: off
7
9
  from .django_test_setup import * # NOQA
@@ -383,6 +385,38 @@ class ComponentMediaTests(SimpleTestCase):
383
385
  ),
384
386
  )
385
387
 
388
+ @override_settings(
389
+ BASE_DIR=Path(__file__).resolve().parent,
390
+ STATICFILES_DIRS=[
391
+ Path(__file__).resolve().parent / "components",
392
+ ],
393
+ )
394
+ def test_component_media_with_dict_with_relative_paths(self):
395
+ from .components.relative_file.relative_file import RelativeFileComponent
396
+
397
+ comp = RelativeFileComponent("")
398
+
399
+ self.assertHTMLEqual(
400
+ comp.render_dependencies(),
401
+ dedent(
402
+ """\
403
+ <link href="relative_file/relative_file.css" media="all" rel="stylesheet">
404
+ <script src="relative_file/relative_file.js"></script>
405
+ """
406
+ ),
407
+ )
408
+
409
+ rendered = comp.render(Context(comp.get_context_data(variable="test")))
410
+ self.assertHTMLEqual(
411
+ rendered,
412
+ """
413
+ <form method="post">
414
+ <input type="text" name="variable" value="test">
415
+ <input type="submit">
416
+ </form>
417
+ """,
418
+ )
419
+
386
420
 
387
421
  class ComponentIsolationTests(SimpleTestCase):
388
422
  def setUp(self):
@@ -48,6 +48,10 @@ class VariableDisplay(component.Component):
48
48
  class IncrementerComponent(component.Component):
49
49
  template_name = "incrementer.html"
50
50
 
51
+ def __init__(self, *args, **kwargs):
52
+ super().__init__(*args, **kwargs)
53
+ self.call_count = 0
54
+
51
55
  def get_context_data(self, value=0):
52
56
  value = int(value)
53
57
  if hasattr(self, "call_count"):
@@ -242,9 +246,13 @@ class ContextCalledOnceTests(SimpleTestCase):
242
246
  "{% load component_tags %}{% component_dependencies %}"
243
247
  "{% component name='incrementer' %}{% endcomponent %}"
244
248
  )
245
- rendered = template.render(Context()).strip()
246
-
247
- self.assertEqual(rendered, '<p class="incrementer">value=1;calls=1</p>', rendered)
249
+ rendered = template.render(Context()).strip().replace("\n", "")
250
+ self.assertHTMLEqual(
251
+ rendered,
252
+ '<link href="relative_file/relative_file.css" media="all" rel="stylesheet">'
253
+ '<script src="relative_file/relative_file.js"></script>'
254
+ '<p class="incrementer">value=1;calls=1</p>',
255
+ )
248
256
 
249
257
  def test_one_context_call_with_simple_component_and_arg(self):
250
258
  template = Template("{% load component_tags %}{% component name='incrementer' value='2' %}{% endcomponent %}")
@@ -1,6 +1,6 @@
1
1
  import re
2
2
  import textwrap
3
- from typing import Callable, Iterable, Optional
3
+ from typing import Callable, Optional
4
4
 
5
5
  from django.template import Context, Template, TemplateSyntaxError
6
6
 
@@ -1250,7 +1250,7 @@ class IterationFillTest(SimpleTestCase):
1250
1250
  class ComponentSimpleSlotInALoop(django_components.component.Component):
1251
1251
  template_name = "template_with_slot_in_a_loop.html"
1252
1252
 
1253
- def get_context_data(self, objects: Iterable) -> dict:
1253
+ def get_context_data(self, objects, *args, **kwargs) -> dict:
1254
1254
  return {
1255
1255
  "objects": objects,
1256
1256
  }
@@ -1,35 +0,0 @@
1
- """
2
- Template loader that loads templates from each Django app's "components" directory.
3
- """
4
-
5
- from pathlib import Path
6
-
7
- from django.conf import settings
8
- from django.template.loaders.filesystem import Loader as FilesystemLoader
9
- from django.template.utils import get_app_template_dirs
10
-
11
-
12
- class Loader(FilesystemLoader):
13
- def get_dirs(self):
14
- component_dir = "components"
15
- directories = set(get_app_template_dirs(component_dir))
16
-
17
- if hasattr(settings, "BASE_DIR"):
18
- path = (Path(settings.BASE_DIR) / component_dir).resolve()
19
- if path.is_dir():
20
- directories.add(path)
21
-
22
- if settings.SETTINGS_MODULE:
23
- module_parts = settings.SETTINGS_MODULE.split(".")
24
- module_path = Path(*module_parts)
25
-
26
- if len(module_parts) > 2:
27
- module_path = Path(*module_parts[:-1])
28
-
29
- # Use list() for < Python 3.9
30
- for parent in list(module_path.parents)[:2]:
31
- path = (parent / component_dir).resolve()
32
- if path.is_dir():
33
- directories.add(path)
34
-
35
- return list(directories)