Django静态URL不工作

2024-04-29 09:05:12 发布

您现在位置:Python中文网/ 问答频道 /正文

Django版本是1.4。我已经阅读了official document,并用谷歌搜索了我的问题。

首先,我遵循了官方文件Managing static filessettings.py中添加的内容:

TEMPLATE_CONTEXT_PROCESSORS = (
  'django.core.context_processors.debug',
  'django.core.context_processors.i18n',
  'django.core.context_processors.media',
  'django.core.context_processors.static',
  'django.contrib.auth.context_processors.auth',
  'django.contrib.messages.context_processors.messages',
)

在我的模板中:

<link href="{{ STATIC_URL }}css/main.css" ...>

但是,在我的兄弟身上是:

<link href="css/main.css" ...> (Just render `STATIC_URL` as empty)

我的设置是:

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

在我的views

def register(request):
    ...
    return render_to_response('register.html', {'errors':errors})

Tags: djangocoreauthurlmaincontextlinkstatic
3条回答

不幸的是,Django的render_to_response快捷方式默认使用普通的模板上下文,它不包括上下文处理程序及其所有花哨和有用的东西,比如STATIC_URL。您需要使用^{},这确实做到了。

这可以通过使用新的^{}(从Django 1.3开始可用)调用:

from django.shortcuts import render

return render(request, 'register.html', {'errors':errors})

在Django 1.2及更高版本中,需要显式地提供上下文:

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('register.html', {'errors':errors},
    context_instance=RequestContext(request))

改变

return render_to_response('register.html', 'errors':errors)

return render_to_response('register.html', {'errors': errors}, RequestContext(request))

在Django 1.4中,应该使用statictemplatetag1

尝试:

{% load staticfiles %}
<link href="{% static "css/main.css" %} ...>

相关问题 更多 >