How to Pass Additional Context into a CBV?

TAGS: DJANGO 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 super call
  • Take care that super suits 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!

Subscribe to my newsletter!
You'll get notified via e-mail when new articles are published. I mostly write about Docker, Kubernetes, automation and building stuff on the web. Sometimes other topics sneak in as well.

Your e-mail address will be used to send out summary emails about new articles, at most weekly. You can unsubscribe from the newsletter at any time.

Für den Versand unserer Newsletter nutzen wir rapidmail. Mit Ihrer Anmeldung stimmen Sie zu, dass die eingegebenen Daten an rapidmail übermittelt werden. Beachten Sie bitte auch die AGB und Datenschutzbestimmungen .

vsupalov.com

© 2024 vsupalov.com. All rights reserved.