Django - 引用模板中的静态文件

Jes*_*ess 10 python django static templates twitter-bootstrap

我在模板中引用静态文件时遇到了困难.我正在使用Twitter Bootstrap并将引导程序文件(css,img,js)放在mysite/static中.

我已经设置了STATIC_URL,STATIC_ROOTTEMPLATE_CONTEXT_PROCESSORS根据本教程.我已经运行./manage.py collectstatic了复制了72个文件.我还将以下模板标记添加到我的template(index.html)文件中,但这没有用.

{% load staticfiles %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen"/>
Run Code Online (Sandbox Code Playgroud)

任何有关如何引用文件的帮助,以便引导程序样式返回到模板将非常感谢!

sup*_*er9 17

它应该是

{% load static from staticfiles %}
Run Code Online (Sandbox Code Playgroud)

然后是类似的东西

<!-- path -->
<link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet" type="text/css">
<!--->
Run Code Online (Sandbox Code Playgroud)

更新完整性

文件夹结构

  • PROJ
    • APP1
    • APP2
    • myproj_public
    • 静态的
      • CSS
        • bootstrap.css
      • JS
        • xyz.js

设置文件

STATIC_ROOT = os.path.join(os.path.abspath(
    os.path.join(PROJECT_ROOT, 'myproj_public', 'static')), '')

STATIC_URL = '/static/'
Run Code Online (Sandbox Code Playgroud)


ers*_*an9 5

您是否user_stylesheet在视图中设置上下文变量?您需要先设置它,然后才能将其传递给模板。

我通常只使用{{ static_url }}标签来做这些事情,所以我的包含引导程序组件的代码会像。

<link href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="{{ STATIC_URL }}bootstrap/js/jquery.js"></script>
Run Code Online (Sandbox Code Playgroud)

假设 bootstrap 文件夹存在于 static 中。

编辑

对于您的情况,要设置user_stylesheet上下文变量,您需要执行以下操作

dict["user_stylesheet"]= <path to your file>
#add other context variables you might have to
render_to_response(<your template name>, dict, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)