Django: Dynamically add apps as plugin, building urls and other settings automatically

后端 未结 5 1358
慢半拍i
慢半拍i 2021-01-03 01:29

I have following structure of my folders in Django:

./project_root
    ./app
       ./fixtures/
       ./static/
       ./templates/
       ./blog/
       ./         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-03 02:04

    I have modified the logic of @wdh and I have tested with Django 2.2.9 (latest stable in Jan 2020) and python 3.8

    urls.py

    from django.apps import apps
    from django.conf import settings
    
    for app in settings.INSTALLED_APPS:
        if app.startswith('myappsprefix_'):
            app_config = apps.get_app_config(app.rsplit('.')[0])
            urlpatterns += i18n_patterns(
                path(f'{app_config.urls}/', include(f'{app_config.name}.urls')),
            )
    

    i18n_patterns is for internationalization.

    apps.py of every app

    class MyCustomAppsConfig(AppConfig):
        name = 'myappsprefix_mycustomapp'
        urls = 'mybaseurlforapp'  # required!
    

    in my settings.py

    INSTALLED_APPS = [
        ...
    
        'myappsprefix_mycustomapp.apps.MyCustomAppsConfig',
        ...
    ]
    

提交回复
热议问题