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

后端 未结 5 1362
慢半拍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 01:58

    What you'll want is something like this:

    from django.utils.importlib import import_module
    for app in settings.INSTALLED_APPS:
    
        try:
            mod = import_module('%s.urls' % app)
            # possibly cleanup the after the imported module?
            #  might fuss up the `include(...)` or leave a polluted namespace
        except:
            # cleanup after module import if fails,
            #  maybe you can let the `include(...)` report failures
            pass
        else:
            urlpatterns += patterns('',
                url(r'^%s/' % slugify(app), include('%s.urls' % app)
            )
    

    You'll also want to steal and implement your own slugify from django template or utils (I'm not exactly sure where it lives these days?) and slightly modify it to strip out any 'dots' and other useless namespacing you don't want in your 'url' e.g. you might not want your urls looking like so: 'example.com/plugin.some_plugin_appname/' but like example.com/nice_looking_appname/

    You might even not want it automagicly named after all, and instead made a configurable 'setting' in your plugins own 'settings' module or something like so:

    # plugin settings conf
    url_namespace = 'my_nice_plugin_url/'
    
    # root urls.py:
    url(r'^%s/' % mod.url_namespace, include(...))
    # or:
    url(r'^%s/' % app.settings.url_namespace, inc..
    

    You probably get the gist of it.

    Kind regards,

提交回复
热议问题