Skip to main content
 首页 » 编程设计

python之Django之urls.py 中的静态文件夹映射

2024年10月24日35over140

我的 Django 应用程序中有以下文件结构

|-myapp 
|---static 
|-----adminapp 
|-----clientapp 
|-----commonapp 
|-----css 
|-----fonts 
|-----js 
|---templates 
|-----administration 
|-------index.html 
|-----client 
|-------index.html 

这是因为我想构建两个 Angular 应用程序,一个用于用户 (static/clientapp),一个用于管理员 (static/adminapp)。

templates/administration/index.html 和 templates/client/index.html 相似,包含如下代码:

<head> 
    <script src="static/js/angular.js"></script> 
    <script src="static/adminapp/app.js"></script> 
</head> 
<body ng-app="adminapp"></body> 

我的管理员和客户端应用程序的链接应该是:

http://example.com/administration/   
http://example.com/client/ 

问题是我应该将什么条目添加到 urls.py 以让两个 Angular 应用程序访问同一个 static 文件夹。

它必须像这样:

url(r'^administration/static/$', STATIC_ROOT), 
url(r'^client/static/$', STATIC_ROOT) 

但我是 django 新手,我不知道如何正确定义它。

请您参考如下方法:

在生产中你不应该让 Django 处理静态文件,所以它应该在你的 nginx/appache 配置中为 administation/static/ 和 client/static/设置正确的路径。

出于开发目的,您可以添加如下内容:

if settings.DEBUG: 
    urlpatterns += [ 
        url(r'^administation/static/(?P<path>.*)$', ' django.views.static.serve', {'document_root': settings.ADMIN_STATIC_ROOT}), 
        url(r'^client/static/(?P<path>.*)$', ' django.views.static.serve', {'document_root': settings.CLIENT_STATIC_ROOT}), 
   ] 

然后您只需在设置中定义ADMIN_STATIC_ROOT 和CLIENT_STATIC_ROOT。