Closed EmilStenstrom closed 1 month ago
@franciscobmacedo I agree that this is not optimal behaviour. There's probably an easy fix that entails putting the components in the a component specific scope instead of the global one. I'll happily accept patches that changes that.
Just a thought since I was dealing with imports yesterday (but for the template/media relative paths), and this seems like a similar issue.
If my project structure is
sampleproject/
├── components/
│ └── select/
│ ├── select.py # <- the problem
│ └── template.html
├── sampleproject/
├── manage.py
└── requirements.txt
then I would expect that the Python import path to for select.py
would be components.select.select
. Hence IMO it should NOT collide with libraries like select
.
I don't think I've used the autodiscover before. So just to be sure, @EmilStenstrom are the autodiscovered files imported and used elsewhere in the code? Or is the whole purpose just to load the component files, so that the component class is registered with @component.register("mycomponent")
?
If it's the latter, then we could possibly skip this assignment since it has has no purpose for Django components:
sys.modules[spec.name] = module
Or alternatively we could try to resolve the autoimported files to a correct module name. E.g. assuming that I ran Django from within the sampleproject
dir, then select.py
would have relative path ./components/select/select.py
, so we would turn that into components.select.select
I'll try to give this a try this weekend.
Btw @franciscobmacedo great work getting to the root of this issue!
Thanks! It took me a while to find out what was the problem - I thought it was something with my python version 😂
@JuroOravec The only purpose of autodiscover is not having to import the component classes manually (import them in your __init__.py
files or whatever). So simply skipping putting them into the global scope sounds like a good idea.
the modules lookup is used in some other places, specifically:
__init_subclass__
method of the Component
, where the component hash is created_resolve_component_relative_files
, where the file path to the component is extractedI believe the module path should be like you said @JuroOravec but I'm not sure how.
I made an initial PR, but it's still not working properly
Hi, I made a separate MR for the fix, as I was just tinkering a lot on my fork: https://github.com/EmilStenstrom/django-components/pull/435
So, simply removing that line of code didn't work, because then the relative paths for templates feature didn't work (as @franciscobmacedo mentioned, in _resolve_component_relative_files
). But what I found is that we can use importlib.import_module
, and then everything works fine.
@franciscobmacedo in that case we can close https://github.com/EmilStenstrom/django-components/pull/434
Discussed in https://github.com/EmilStenstrom/django-components/discussions/430