2

我想通过 Django 中的多个包含标签传递“上下文”变量,如下所示:

base.html:

{% load extras %}
{% table_of_contents course %}

目录表.html:

{% load extras %}

<h1>Table of contents</h1>
{% for section in course.sections %}
    {% display_section section %}
{% endfor %}

额外的.py:

@register.inclusion_tag('table-of-contents.html', takes_context=True)
def table_of_contents(context, course):

    return {
        'course': course,
    }

@register.inclusion_tag('display_section.html', takes_context=True)
def section_expanded(context, section):

    # Identify the user from the context request
    user = context['request'].user

    return {
        'section': section,
        'completed': section.has_been_completed_by(user),
        'outstanding_modules': section.get_outstanding_modules_for(user)
    }

但是,当我运行上面的代码时,我得到一个关键错误,因为上下文变量没有传递到第二个包含标记:

KeyError at /courses/pivottables-video-course/table-of-contents/
'request'

如何确保上下文变量在传递到多个嵌套包含标记时仍然存在?

4

1 回答 1

4

你正在return {'foo': 'bar'}为你的模板定义新的上下文——这个新的上下文不包含request键。默认情况下context['request']request上下文处理器设置(https://docs.djangoproject.com/en/dev/ref/templates/api/#django-template-context-processors-request)。

如果你想context['request']通过多个标签,你可以这样做:

@register.inclusion_tag('table-of-contents.html', takes_context=True)
def table_of_contents(context, course):

    return {
        # ...
        'request': context.get('request'),
        # ...
    }

@register.inclusion_tag('display_section.html', takes_context=True)
def section_expanded(context, section):

    # Identify the user from the context request
    user = context['request'].user

    return {
        # ...
        'request': context.get('request'),
        # ...
    }
于 2017-05-03T22:11:08.660 回答