|
| 1 | +import importlib |
| 2 | +import logging |
| 3 | + |
| 4 | +from django.apps import apps |
| 5 | +from django.conf import settings |
| 6 | +from django.conf.urls import url, include |
| 7 | +from django.conf.urls.static import static |
| 8 | +from django.contrib import admin |
| 9 | +from django.urls import path |
| 10 | + |
| 11 | + |
| 12 | +def dynamic_url(): |
| 13 | + _urlpatterns = [url(r"admin/", admin.site.urls)] + ( |
| 14 | + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
| 15 | + if settings.MEDIA_ROOT |
| 16 | + else [] |
| 17 | + ) |
| 18 | + |
| 19 | + """ |
| 20 | + Here, apps are registered automatically with their urls if they have a property "url_prefix" set in their AppConfig |
| 21 | + AND if they have a valid urls.py file which sets a variable urlpatterns |
| 22 | + """ |
| 23 | + for config in apps.get_app_configs(): |
| 24 | + if hasattr(config, "url_prefix"): |
| 25 | + logging.debug( |
| 26 | + f"Found url_prefix in {config.name}, checking for .urls module" |
| 27 | + ) |
| 28 | + urls_path = config.module.__name__ + ".urls" |
| 29 | + try: |
| 30 | + importlib.import_module(urls_path) |
| 31 | + except ModuleNotFoundError: |
| 32 | + logging.debug(f"No url module found under {urls_path}", exc_info=True) |
| 33 | + continue |
| 34 | + |
| 35 | + logging.debug( |
| 36 | + f"urls.py present under {urls_path}, setting for prefix {config.url_prefix}" |
| 37 | + ) |
| 38 | + # Do the include |
| 39 | + _urlpatterns.append(path(config.url_prefix + "/", include(urls_path))) |
| 40 | + |
| 41 | + logging.debug(f"Patterns: {_urlpatterns}") |
| 42 | + |
| 43 | + return _urlpatterns |
| 44 | + |
| 45 | + |
| 46 | +urlpatterns = dynamic_url() |
0 commit comments