STATIC_URL在基本Django模板中未定义

Ult*_*urd 10 python django static

我有一个模板,base.html在其他几个模板中用于各种视图.每个模板都以适当的方式开头{% extends "base.html" %}.在基本模板中,我想要指定一个静态样式表:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/base.css"/>
Run Code Online (Sandbox Code Playgroud)

但是,当它渲染我的大多数模板时,其值为STATIC_URL空,因此该属性仅是href="/base.css",不加载.该变量是为我绑定到默认登录视图的模板正确定义的django.contrib.auth.views.login,但对于我自己的自定义视图,它是未定义的.

我只是想在开发环境中使用它runserver,因此CSS文件位于应用程序的静态子目录中.

以下是我的相关位settings.py,它们都是默认值:

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

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',
)
Run Code Online (Sandbox Code Playgroud)

在我,urls.py我也补充说:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

#...

urlpatterns += staticfiles_urlpatterns()
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?据我所知,这是基于1.3文档在开发中提供特定于应用程序的静态文件所应该做的.

dan*_*era 21

也许这可以帮助:

如果{{STATIC_URL}}在模板中不起作用,则在渲染模板时可能不会使用RequestContext.作为简要回顾,上下文处理器将变量添加到每个模板的上下文中.但是,上下文处理器要求您在呈现模板时使用RequestContext.如果您使用的是通用视图,则会自动执行此操作,但在手动编写的视图中,您需要显式使用RequestContext要查看其工作原理,并阅读更多详细信息,请查看Subclassing Context:RequestContext.

  • 这使我朝着正确的方向前进.(你引用的部分是[这里](https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext))我没有用`context_instance =调用`render_to_response`的RequestContext(请求)`. (2认同)
  • 如果您使用的是Django 1.3,则无需手动传入context_instance.渲染快捷方式将为您执行此操作:return render(request,'the-template.html',{'foo':'bar'}) (2认同)

Nic*_*ran 15

您需要将"django.core.context_processors.static"添加到settings.py中的TEMPLATE_CONTEXT_PROCESSORS变量中.