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
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 the context object using a
- 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
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
get_context_data. Just modify the
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.
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!