Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 422
ataush Avatar asked Aug 01 '18 11:08

ataush


1 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).

like image 117
Willem Van Onsem Avatar answered Nov 14 '22 22:11

Willem Van Onsem