Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Pass context through multiple nested inclusion tags in Django

I'd like to pass the 'context' variable through multiple inclusion tags in Django like so:

base.html:

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

table-of-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)
    }

However, when I run the code above, I get a key error because the context variable is not passed through to the second inclusion tag:

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

How can I ensure that the context variable persists when passed through to multiple nested inclusion tags?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You're defining new context with return {'foo': 'bar'} for your templates – and this new context doesn't contain request key. By default context['request'] is set by request context processor (https://docs.djangoproject.com/en/dev/ref/templates/api/#django-template-context-processors-request).

If you want to pass context['request'] through multiple tags, you can do this:

@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'),
        # ...
    }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!