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

后端 未结 5 1359
慢半拍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:03

    I've modified @Progressify's code a bit further to do away with the app prefix.

    # in your project's urls.py
    from django.apps import apps
    from django.contrib import admin
    from django.conf import settings
    from django.urls import include, path
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        # ...
        # any other paths you may have
    ]
    
    # Load urls from any app that defines a urls attribute in appname.apps.AppConfig
    for app in settings.INSTALLED_APPS:
        try:
            app_config = apps.get_app_config(app.rsplit('.')[0])
            try:
                urls = app_config.urls
                urlpatterns += [
                    path(f'{app_config.urls}', include(f'{app_config.name}.urls', namespace=f'{app_config.urls_namespace}')),
                ]
            except AttributeError:
                pass
                
        except LookupError:
            pass
    

    This will look for an AppConfig in your project's apps.py that defines a prefix and a namespace, and include those accordingly. Admittedly the error catching is a bit crude, so you may want to refine it a bit depending on whether you want to allow your app to define urls but not a namespace, etc.

    # in each of your apps' apps.py
    from django.apps import AppConfig
    
    class UsersConfig(AppConfig): # name the class whatever you want
        name = 'users'            # name of your app
        urls = ''                 # prefix for this app's urls –– may need to append slash
        urls_namespace = 'users'  # app url namespace –– it's "best practice" to define one
    

提交回复
热议问题