一直很纠结的一个问题,网络上也有很多方案,但总感觉不完美.
之前的方案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
1 . 在setting.py中
STATIC_ROOT =
'static/'
STATIC_URL =
'static/'
2. 在模板页面中
<link rel=
"stylesheet"
href=
"{{ STATIC_URL }}css/bootstrap.css"
>
<script
type
=
"text/javascript"
src=
"{{ STATIC_URL }}js/bootstrap.js"
><
/script
>
3. 在urls.py的配置中
from django.conf.urls.static
import
static
urlpatterns = patterns(
''
,
url(r
'^admin/'
, include(admin.site.urls)),
(r
'^$'
, latest_books),
) + (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
4. 在views.py对应的输出视图中
return
render_to_response(
'index.html'
, {
'book_list'
: book_list,
'STATIC_URL'
: STATIC_URL,
})
|
虽然能解决一定问题但是每一回都需要在response中添加STATIC_URL,非常烦躁
结合最近的项目部署以及开发深入,总结完美方案一套
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
1. 在settings.py中
STATIC_URL =
'/static/'
STATIC_ROOT =
'/static/'
STATICFILES_DIRS = (
os.path.
join
(BASE_DIR,
'static'
).replace(
'\\'
,
'/'
),
)
2. 在url.py中(总路由 即全局路由出口)
urlpatterns = patterns(
''
,
url(r
'^admin/'
, include(admin.site.urls)),
url(r
'^app/'
, include(
'app.urls'
)),
) + (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
3. 在模板视图中
<link rel=
"stylesheet"
href=
"{{ STATIC_URL }}css/bootstrap.css"
>
<script
type
=
"text/javascript"
src=
"{{ STATIC_URL }}js/bootstrap.js"
><
/script
>
|
这样在views中的每个视图方法就不需要重复response STATIC_URL了
本文转自My_King1 51CTO博客,原文链接:http://blog.51cto.com/apprentice/1532733,如需转载请自行联系原作者