How to Pass Additional Context into a CBV?
Passing context into your templates from class-based views is easy once you know what to look out for.
There are two ways to do it - one involves get_context_data,
the other is a bit less known, but can be pretty useful.
Are you trying to add keys to your context dict, but they are not working as expected? Here’s a quick checklist to see if you’re not missing something important:
- Name the function responsible for context
get_context_data - Get the context object using a
supercall - Take care that
supersuits your Python version (it makes a difference whether you use Python 2 or 3 – see the example below) - Set the field name to a reliable string-key (lower case letters and underscores is what I like to use)
- Don’t forget to return your modified context object from the function
An example
Here is what the get_context_data function should look like:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
new_context_entry = "here it goes"
context["new_context_entry"] = new_context_entry
return context
Above is the Python 3.x version. Please note, that if you’re using Python 2.x, your ‘super’ line has to look different:
def get_context_data(self, *args, **kwargs):
context = super(CBV_NAME, self).get_context_data(*args, **kwargs)
new_context_entry = "here it goes"
context["new_context_entry"] = new_context_entry
return context
Be sure to replace CBV_NAME with the actual name of your CBV.
A second approach: quick context values
You can assign a value to extra_context from a function which is
not get_context_data. Just modify the extra_context variable
from inside a function of your CBV:
self.extra_context["another_one"] = "here goes more"
This will be processed, to add the key to your context automagically.
Conclusion
Above, you have seen two ways to add a new key to the CBV context dictionary. If you’ve had an error, I hope that the checklist has helped you to trace it down.
Using those approaches, you should keep all previous context variables and be able to add new entries. I hope this helped you to avoid CBV trouble when creating a context to be passed to your Django templates. Happy coding!
A word from the author
Hi, I'm Vladislav. I work with small teams and bootstrapped founders who need to get their infrastructure right — reliable deployments, less operational risk, and systems that don't fall apart the moment the founder looks away. If that sounds like your situation, here's how we can work together.
I've been writing about Docker, deployment, and infrastructure since 2017. If you'd like to read more, the articles page is a good place to start — or you can sign up for the newsletter to get new pieces by email.