【问题标题】:How to use external static files with Django (serving external files once again)?如何在 Django 中使用外部静态文件(再次提供外部文件)?
【发布时间】:2011-06-05 19:31:10
【问题描述】:

即使在 Google 上搜索并阅读了 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">

我正在尝试使用存储在“静态”目录中的 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 时,当我在浏览器中打开我的应用程序时得到一个空白页面。

我正在使用: 视窗 Python 2.6.4 Django 1.2.3

非常感谢您的帮助

【问题讨论】:

    标签: django file static


    【解决方案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'
    

    【讨论】:

    • 不幸的是,它仍然不起作用。感谢您提供有关导入设置的建议。
    • 查看 Django 显示给你的调试页面或在某处分享。
    • 如果我在浏览器中打开我的应用程序,我没有得到调试页面,但我得到一个空白页面 :-( 我编辑了问题以提供更多信息。
    • 因此,在 settings.py 中:MEDIA_ROOT = os.path.join(SITE_ROOT, 'static') MEDIA_URL = '/static/' 并在模板中: ?我仍然得到一个空白页。
    • 如果设置中有 DEBUG = True 则应该获得 Django 调试页面,如果没有则获得 404 Not Found 页面。
    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2013-12-02
    相关资源
    最近更新 更多