django-components 0.52__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.52 → django_components-0.60}/PKG-INFO +69 -5
  2. {django_components-0.52 → django_components-0.60}/README.md +68 -4
  3. {django_components-0.52 → django_components-0.60}/django_components/__init__.py +4 -9
  4. {django_components-0.52 → django_components-0.60}/django_components/component.py +98 -0
  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.52 → django_components-0.60}/django_components.egg-info/PKG-INFO +69 -5
  8. {django_components-0.52 → django_components-0.60}/django_components.egg-info/SOURCES.txt +1 -0
  9. {django_components-0.52 → django_components-0.60}/setup.py +1 -1
  10. {django_components-0.52 → django_components-0.60}/tests/test_autodiscover.py +30 -9
  11. {django_components-0.52 → django_components-0.60}/tests/test_component.py +34 -0
  12. {django_components-0.52 → django_components-0.60}/tests/test_context.py +7 -3
  13. django_components-0.52/django_components/template_loader.py +0 -35
  14. {django_components-0.52 → django_components-0.60}/LICENSE +0 -0
  15. {django_components-0.52 → django_components-0.60}/django_components/app_settings.py +0 -0
  16. {django_components-0.52 → django_components-0.60}/django_components/apps.py +0 -0
  17. {django_components-0.52 → django_components-0.60}/django_components/component_registry.py +0 -0
  18. {django_components-0.52 → django_components-0.60}/django_components/management/__init__.py +0 -0
  19. {django_components-0.52 → django_components-0.60}/django_components/management/commands/__init__.py +0 -0
  20. {django_components-0.52 → django_components-0.60}/django_components/management/commands/startcomponent.py +0 -0
  21. {django_components-0.52 → django_components-0.60}/django_components/management/commands/upgradecomponent.py +0 -0
  22. {django_components-0.52 → django_components-0.60}/django_components/middleware.py +0 -0
  23. {django_components-0.52 → django_components-0.60}/django_components/safer_staticfiles/__init__.py +0 -0
  24. {django_components-0.52 → django_components-0.60}/django_components/safer_staticfiles/apps.py +0 -0
  25. {django_components-0.52 → django_components-0.60}/django_components/templatetags/__init__.py +0 -0
  26. {django_components-0.52 → django_components-0.60}/django_components/templatetags/component_tags.py +0 -0
  27. {django_components-0.52 → django_components-0.60}/django_components/types.py +0 -0
  28. {django_components-0.52 → django_components-0.60}/django_components.egg-info/dependency_links.txt +0 -0
  29. {django_components-0.52 → django_components-0.60}/django_components.egg-info/requires.txt +0 -0
  30. {django_components-0.52 → django_components-0.60}/django_components.egg-info/top_level.txt +0 -0
  31. {django_components-0.52 → django_components-0.60}/pyproject.toml +0 -0
  32. {django_components-0.52 → django_components-0.60}/setup.cfg +0 -0
  33. {django_components-0.52 → django_components-0.60}/tests/components/__init__.py +0 -0
  34. {django_components-0.52 → django_components-0.60}/tests/components/single_file.py +0 -0
  35. {django_components-0.52 → django_components-0.60}/tests/components/urls.py +0 -0
  36. {django_components-0.52 → django_components-0.60}/tests/test_component_as_view.py +0 -0
  37. {django_components-0.52 → django_components-0.60}/tests/test_dependency_rendering.py +0 -0
  38. {django_components-0.52 → django_components-0.60}/tests/test_registry.py +0 -0
  39. {django_components-0.52 → django_components-0.60}/tests/test_settings.py +0 -0
  40. {django_components-0.52 → django_components-0.60}/tests/test_startcomponent_command.py +0 -0
  41. {django_components-0.52 → django_components-0.60}/tests/test_templatetags.py +0 -0
  42. {django_components-0.52 → 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.52
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)
@@ -1,5 +1,6 @@
1
1
  import difflib
2
2
  import inspect
3
+ import os
3
4
  from collections import ChainMap
4
5
  from typing import Any, ClassVar, Dict, Iterable, List, Optional, Set, Tuple, Union
5
6
 
@@ -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,6 +37,7 @@ 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):
@@ -60,9 +63,104 @@ class SimplifiedInterfaceMediaDefiningClass(MediaDefiningClass):
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.
@@ -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,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.52
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
@@ -3,7 +3,7 @@ import os
3
3
 
4
4
  from setuptools import find_packages, setup
5
5
 
6
- VERSION = "0.52"
6
+ VERSION = "0.60"
7
7
 
8
8
  setup(
9
9
  name="django_components",
@@ -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):
@@ -246,9 +246,13 @@ class ContextCalledOnceTests(SimpleTestCase):
246
246
  "{% load component_tags %}{% component_dependencies %}"
247
247
  "{% component name='incrementer' %}{% endcomponent %}"
248
248
  )
249
- rendered = template.render(Context()).strip()
250
-
251
- 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
+ )
252
256
 
253
257
  def test_one_context_call_with_simple_component_and_arg(self):
254
258
  template = Template("{% load component_tags %}{% component name='incrementer' value='2' %}{% endcomponent %}")
@@ -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)