EmilStenstrom / django-components

Create simple reusable template components in Django.
MIT License
973 stars 62 forks source link

Autodiscover #24

Closed danjac closed 3 years ago

danjac commented 3 years ago

Tests pass but this should probably be tested manually in an example app.

EmilStenstrom commented 3 years ago

This looks great! I don't follow the flow here, would you mind explaining it to me?

  1. First __init__.py is initialized by Python
  2. autodiscover_modules loads all components.py files and adds them to LIBRARIES?
  3. That is then loaded with import_module?
  4. What do the two other files do?
danjac commented 3 years ago

The app_settings module lets us set some defaults in Django settings. These are the defaults:

COMPONENTS = {
    "autodiscover": True,
   "libraries": []
}

If "autodiscover" is True then any "components.py" module under your apps is automatically loaded at startup - so you can put any components in a components.py module and call component.registry.register() and they will be loaded.

In addition you can list any specific modules in your settings under "libraries": for example, you might have a generic "Button" component that doesn't really belong in any specific app, and it goes in a module called "common_components":

COMPONENTS = {
    "autodiscover": True,
   "libraries": ["mysite.common_components"]
}

We set the apps config to automatically run at startup:

https://docs.djangoproject.com/en/3.1/ref/applications/

When autodiscover() is run, it loads the app settings. The autodiscover_modules call is run (assuming "autodiscover" is True) and this will automatically run through all installed apps and load any "components" module. This is how Django admin works by the way: it automatically loads any "admin" module under installed apps.

We then run import_module() on any string under "libraries".

EmilStenstrom commented 3 years ago

@danjac Thank you for the explanation! I'll definitely merge this, it's a great addition.

Do you want to take a stab at adding documentation to the README too, or should I try?

danjac commented 3 years ago

Thanks @EmilStenstrom! Sure I can give it a go.

EmilStenstrom commented 3 years ago

Released to PyPI as version 0.7! Thanks.

danjac commented 3 years ago

Thanks! Great work on this library btw - Django needs an equivalent to LiveWire and Rails view components.

EmilStenstrom commented 3 years ago

@danjac Thanks! I totally agree. Will happily accept more PR:s if you want to add more bells and whistles.