如何使用Django的外部静态文件(再次提供外部文件)?

时间:2011-01-08 16:30:43

标签: django file static

即使在谷歌搜索和阅读StackOverflow上的所有相关帖子后,我仍然无法在我的Django应用程序中获取静态文件。

我正在使用开发服务器,以下是我的文件的外观:

settings.py

MEDIA_ROOT = os.path.join(SITE_ROOT, 'static')
MEDIA_URL = '/static/'

urs.py

from DjangoBandCreatorSite.settings import DEBUG
if DEBUG:
    urlpatterns += patterns('', (
        r'^static/(?P<path>.*)$',
        'django.views.static.serve',
        {'document_root': 'static'}
    ))

模板:

<script type="text/javascript" src="/static/jquery.js"></script>
<script type="text/javascript">

我正在尝试使用存储在“static”目录中的jquery.js。

这是我模板的完整代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <style>

      span 
      {
        color: blue;
        text-decoration:underline;
        cursor: pointer;
      }
      .nav{
        font-weight: bold;
        font-size: large;
        color: cadetblue;
      }

    </style>

    <script type="text/javascript" src="/static/jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    {

       $.get("content.html", addContent);   // calls addContent() with argument "content.html"

       function addContent(data)            // fills <div id='content'> with what gets as an argument (in this template, it is "content.html")
       {
          $("#content").html(data);          
       }
    </script>
</head>

<body>
  <div id="content">
  {% block content %}{% endblock %}
    <!--THE RETURN VALUE OF addContent() IS INSERTED HERE-->
  </div>
</body>
</html>

如果我使用src =“http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js”

而不是src =“/ static / jquery.js”

脚本标签中的

一切正常。但是当我尝试使用/static/jquery.js时,我在浏览器中打开应用程序时会出现一个空白页面。

我正在使用: Windows XP Python 2.6.4 Django 1.2.3

非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您没有为static_serve视图正确设置document_root。另请注意应如何导入设置。

from django.conf import settings

# ...

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^%s/(?P<path>.*)$'  % settings.MEDIA_URL.strip('/'),
            'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT,
             'show_indexes': True}),
    )

这适用于Django 1.2,1.3中存在一些差异。如果这没有用,请尝试在设置中添加一些断言:

assert MEDIA_ROOT == r'your/path/here'