Django:STATIC_URL在URL中添加应用名

2 投票
1 回答
1455 浏览
提问于 2025-04-17 01:28

我已经这样配置了我的静态设置:

STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    ('js', os.path.join(STATIC_ROOT, 'js')),
    ('css', os.path.join(STATIC_ROOT, 'css')),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#   'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

然后在我的 urls.py 文件中做了这些设置:

urlpatterns = patterns('',
    url(r'^login/?$', login, name='login'),
    url(r'^logout/?$', logout_then_login, name='logout'),

    url(r'^profile/(?P<user_id>\d+)$', 'profiles.views.detail'),
    url(r'^profile/edit$', 'profiles.views.edit'),
)

urlpatterns += staticfiles_urlpatterns()

这在访问 localhost:8000/login 时运行得很好,但当我访问 localhost:8000/profile/edit 这个页面时,它是由我的 profiles 应用处理的,结果 {{ STATIC_URL }} 把所有的路径从 /static/... 改成了 /profile/static/...,这样我的 JavaScript 文件和样式表就找不到了。

我哪里做错了呢?

编辑:这是我的 base.html 文件:

<!DOCTYPE html>
<html>
    <head>
        <title>Neighr{% block title %}{% endblock %}</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.min.js"></script>
        {% block script %}{% endblock %}
    </head>
    <body>
        {% block content %}{% endblock %}
    </body>
</html>

1 个回答

3

因为你正在使用Django自带的开发服务器,试着从你的 urls.py 文件中去掉以下这一行:

urlpatterns += staticfiles_urlpatterns()

在正式环境中,最好不要用Django来提供静态文件,所以要使用 collectstatic 命令。

编辑

如果是在 settings.py 文件中,可以试试这样:

STATIC_ROOT = os.path.join(os.path.dirname(__file__), '../../static')
STATIC_URL = '/static/'

撰写回答