0

我无法MEDIA_URL在基于类的视图中访问。

我的理解是我会创建我的视图,我的上下文处理器会将它提供到我的基于函数的视图中。现在我正在尝试切换到基于类,并且我不再可以访问MEDIA_URL.

上下文处理器不能与基于类的视图一起使用吗?我现在必须手动将它添加到我的上下文中吗?

这是我的处理器:

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

我以前的观点看起来像:

def my_view(request):
    context = {
        "foo": "bar"
    }
    return render(request, 'index.html', context)

我将能够使用{{MEDIA_URL}}.

我的基于类的视图如下所示:

class MyView(View):
    def get(self, request):
        context = {
            "foo": "bar"
        }
        return render(request, 'index.html', context)

而且我无法访问{{MEDIA_URL}}

4

1 回答 1

2

Django 1.8 moved the configuration of TEMPLATE_CONTEXT_PROCESSORS to the TEMPLATES setting. Beyond that I don't think you shouldn't need to access MEDIA_URL in the template. It's a bad code smell to me. You should be using the url generated from the file storage api (i.e. {{ model.field.url }}).

于 2015-06-19T20:31:13.337 回答