0

我有一个名为 STATIC_URL 的变量,在我的基础项目的 settings.py 中声明:

STATIC_URL = '/site_media/static/'

例如,在我的 site_base.html 中使用它,它链接到 CSS 文件,如下所示:

<link rel="stylesheet" href="{{ STATIC_URL }}css/site_tabs.css" />

我有一堆与扩展 site_base.html 的不同应用程序相关的模板,当我在浏览器中查看它们时,CSS 正确链接为

<link rel="stylesheet" href="/site_media/static/css/site_tabs.css" />

(这些带有默认的 pinax 发行版。)我创建了一个名为“课程”的新应用程序,它位于 ...../apps/courses 文件夹中。我有一个名为 courseinstance.html 的课程页面的视图,它像其他页面一样扩展了 site_base.html。

但是,当这个在我的浏览器中呈现时,它会显示为

<link rel="stylesheet" href="css/site_tabs.css" />

就好像这个应用程序的 STATIC_URL 等于 ""。我是否必须进行某种声明才能让我的应用程序采用与项目相同的变量值?我没有该应用程序的 settings.py 文件。顺便说一句,该应用程序列在我的 INSTALLED_APPS 列表中,并且可以正常运行,只是没有指向 CSS 文件的链接(因此页面看起来很有趣)。

在此先感谢您的帮助。

4

2 回答 2

2

Variables in settings.py are not available to the templates. What is available to a template is determined by the view that renders it. When the template is rendered you pass in a dictionary which is the "context" for the template. The context is a dictionary of names of variables and their values.

To pass a value from the settings onto the template, you usually have to something like this:

from django.conf import settings
def my_view(request):
    # view logic
    context = {
            'STATIC_URL': settings.STATIC_URL,
            # other template variables here
    }
    # render the template and produce a response

Your STATIC_URL settings seems to be very similar to the MEDIA_URL setting.

MEDIA_URL is made available to all templates via a default context processor. You can do something similar by writing your own context processor. You can take a look at how the default context processors are implemented in the django source to get an idea.

于 2010-05-30T01:08:19.050 回答
0
def courseinstance(request, courseinstance_id):
    p = get_object_or_404(CourseInstance, pk=courseinstance_id)
    return render_to_response('courses/courseinstance.html', {'courseinstance': p},
        context_instance=RequestContext(request)) #added this part to fix problem
于 2010-05-30T01:19:12.793 回答