django 将静态路径添加到当前 url [英] django adding static path to current url

查看:28
本文介绍了django 将静态路径添加到当前 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的静态文件位于应用程序目录的 assets 文件夹中.当我转到主页 (/) 时,静态文件从 /assets/ 加载得非常好.如果我转到 /house/,它会尝试从 /house/assets/ 加载静态文件,这显然会导致文件不加载,因为它们不存在.

I have my static files in a folder assets in the application directory. When I go to the main page (/), the static files are being loaded perfectly fine from /assets/. If I go to /house/, it tries to load the static files from /house/assets/, which obviously results in the files not loading as they are not there.

这可能是 settings.py 的相关部分:

This is the possibly relevant piece of settings.py:

...
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
STATIC_PATH = os.path.join(BASE_DIR, 'assets')
STATIC_URL = os.path.join(BASE_DIR,'/assets/')

STATICFILES_DIRS = (
    STATIC_PATH,
)
TEMPLATE_DIRS = (
    TEMPLATE_PATH,
)
...

我正在使用这样的东西在模板中加载静态文件:

I am loading the static files in the templates using something like this:

<link href="assets/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/>

这是应用程序那部分的 urls 文件:

This is the urls file for that part of the application:

urlpatterns = patterns('',
    url(r'^$', views.dashboard, name='dashboard'),
    url(r'^house/$', views.house, name='house'),
)

这些是视图:

def dashboard(request):
    return render_to_response('index.html')

def house(request):
    return render_to_response('house.html')

过去一个小时我一直在寻找解决方案,但没有成功.我发现 这篇文章 提出了类似的问题,但确实如此没有帮助.任何帮助将不胜感激.

I have been looking for a solution to this for the past hour with no success. I have found this post asking a similar thing but it did not help. Any help will be greatly appreciated.

推荐答案

您应该将模板中的 HTML 标记从

You should change the HTML tag in your template from

<link href="assets/plugins/uniform/css/uniform.default.css"
      rel="stylesheet" type="text/css"/>

<link href="/assets/plugins/uniform/css/uniform.default.css"
      rel="stylesheet" type="text/css"/>

请注意相对 URL 前面的斜线 /.如果没有它,浏览器将假定 assets 目录是当前目录的子目录.有了它,它总是从根目录开始.

Please note the slash / in front of the relative URL. Without it, the browser will assume that assets directory is a subdirectory of the current one. With it, it will always start from the root directory.

这篇关于django 将静态路径添加到当前 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆