Why use get_context_data (self,**kwargs) and super ()

Question:

In a class-based view, I simply use get_context_data as a function but why

class CBV (TemplateView):

    def get_context_data(self,**kwargs):
        context = super ().get_context_data  (**kwargs)
Asked By: ataush

||

Answers:

Like the documentation on get_context_data [Django-doc] says:

Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. (..)

If you thus let the function return a dictionary {'foo': 42}, then in your template you can write a variable {{ foo }}, and then it will be replaced with 42.

This is frequently used to pass all kinds of data to a template: the user that is logged in, forms, querysets, etc. The template can then render these components accordingly.

A typical use case is:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['number'] = random.randrange(1, 100)
    return context

Where thus here the “child class” adds an extra element number to the context.

Here we thus make a call to next function in the method resolution order (MRO). This is typically the parent of a class, although the rules of the MRO are a bit more complex in the case of multiple inheritance. The reason is that these parents can add data to the context as well. So by calling the get_context_data of the parent, the parent returns a dictionary that might contain some data already, and then the child(ren) can each in turn add more data to the context (or change it), in reverse MRO order. This however only will happen if every child performs a super().get_context_data(**kwargs) call, and patches the result (and thus not construct a new dictionary).

Answered By: Willem Van Onsem

I had the same question and the only use case I see for accepting **kwargs in get_context_data is to lower the priority of your context variable. This ensures that it will be overridden by any other mixin or parent class if present. Otherwise, providing a resulting dictionary update will have a different effect due to the MRO position of this mixin.

class LowPrioContextMixIn:
  def get_context_data(self, **kwargs):
     return super().get_context_data(low_prio_var=True, **kwargs)
Answered By: Alexander Klimenko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.