天天看點

Django靜态檔案輸出

一直很糾結的一個問題,網絡上也有很多方案,但總感覺不完美.

之前的方案

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.  在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>