我想通过Django中的多个包含标记传递'context'变量,如下所示:
base.html文件:
{% load extras %}
{% table_of_contents course %}
表的-contents.html:
{% load extras %}
<h1>Table of contents</h1>
{% for section in course.sections %}
{% display_section section %}
{% endfor %}
extras.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'
如何确保在传递给多个嵌套包含标记时上下文变量仍然存在?
答案 0 :(得分:1)
您为模板定义了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'),
# ...
}