我在 Django 中的文件夹结构如下:
./project_root
./app
./fixtures/
./static/
./templates/
./blog/
./settings.py
./urls.py
./views.py
./manage.py
./__init__.py
./plugin
./code_editor
./static
./templates
./urls.py
./views.py
./__init__.py
./code_viewer
./static
./templates
./urls.py
./views.py
./__init__.py
那么,如何让根 urls.py 根据 INSTALLED_APPS 通过查找其他 urls.py 来自动构建 url 列表?我更改了 settings.py 以动态构建 INSTALLED_APPS、TEMPLATES_DIR、STATICFILES_DIRS。(这意味着我不知道在不同的服务器上会安装多少插件。它应该在运行时动态检查并添加它。)on:
python manage.py runserver
这是添加 INSTALLED_APPS、TEMPATS_DIR、STATICFILES_DIR 的代码。
PLUGINS_DIR = '/path_to/plugins/'
for item in os.listdir(PLUGINS_DIR):
if os.path.isdir(os.path.join(PLUGINS_DIR, item)):
plugin_name = 'app.plugins.%s' % item
if plugin_name not in INSTALLED_APPS:
INSTALLED_APPS = INSTALLED_APPS+(plugin_name,)
template_dir = os.path.join(PLUGINS_DIR, '%s/templates/' % item)
if os.path.isdir(template_dir):
if template_dir not in TEMPLATE_DIRS:
TEMPLATE_DIRS = TEMPLATE_DIRS+(template_dir,)
static_files_dir = os.path.join(PLUGINS_DIR, '%s/static/' % item)
if os.path.isdir(static_files_dir):
if static_files_dir not in STATICFILES_DIRS:
STATICFILES_DIRS = STATICFILES_DIRS + (static_files_dir,)
任何帮助将不胜感激。先感谢您。
解决方案:
编辑:所以我所做的如下:
我包括两个这样的模块:
from django.conf import settings
from django.utils.importlib import import_module
然后在根 urls.py 中添加以下代码:
def prettify(app):
return app.rsplit('.', 1)[1]
for app in INSTALLED_APPS:
try:
_module = import_module('%s.urls' % app)
except:
pass
else:
if 'eats.plugins' in app:
urlpatterns += patterns('',
url(r'^plugins/%s/' % prettify(app), include('%s.urls' % app))
)
非常感谢@Yuka。谢谢你。谢谢你。谢谢你。谢谢你.... 你让我开心。