首页 > 代码库 > Django静态文件输出

Django静态文件输出

一直很纠结的一个问题,网络上也有很多方案,但总感觉不完美.

之前的方案

1 .  在setting.py中
    STATIC_ROOT = ‘static/‘
    STATIC_URL = ‘static/‘
    
2.  在模板页面中
    <link rel="stylesheet" href="http://www.mamicode.com/{{ STATIC_URL }}css/bootstrap.css">
    <script type="text/javascript" src="http://www.mamicode.com/{{ 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="http://www.mamicode.com/{{ STATIC_URL }}css/bootstrap.css">
<script type="text/javascript" src="http://www.mamicode.com/{{ STATIC_URL }}js/bootstrap.js"></script>

这样在views中的每个视图方法就不需要重复response STATIC_URL了

本文出自 “Apprentice” 博客,请务必保留此出处http://apprentice.blog.51cto.com/2214645/1532733