R
R
RqL2020-12-21 11:33:59
Django
RqL, 2020-12-21 11:33:59

How does get_context_data work in Django?

I'm new to Django and recently learned about the ListView and DetailView classes, the documentation talked about adding extra data to the passed context. I didn’t understand from whom context is inherited in get_context_data and why this function is called with the transfer of a dictionary, it looks like this for me

def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        #context['title'] = 'Название страницы'
        return context

It was also described in the documentation with the DetailView class, but it also works with the ListView class, then what is the difference between these classes?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2020-12-21
@RqL

I did not understand from whom context is inherited in get_context_data

These are mixin methods that use both ListView and DetailView.
See the source code of Django where it is quite clear where what is taken from and from whom it is inherited.
and why is this function called with a dictionary passed,

Usually it is called to get the default context - in other words - variables that can be used in templates, and add some of your own variables there.
It was also described in the documentation with the DetailView class, but it also works with the ListView class, then what is the difference between these classes

Go and get acquainted with the basic knowledge for working with OOP - encapsulation, polymorphism, inheritance ...

D
Dr. Bacon, 2020-12-21
@bacon

ListView for a list of
DetailView objects for one specific object
Each class has a hierarchy of ancestors, and inheritance comes from them. Through super you call get_context_data of the immediate ancestor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question