Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django/Python: understanding how super is used in function

Tags:

python

django

I am just beginning to wrap my head around what super is and how it is implemented in view based classes in Django. I am trying to understand how super is working in the following code. Could someone try to break it down for me piece by piece?

from django.views.generic.detail import DetailView
from apps.app_name.models import Article

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'article/show.html'

    def get_context_data(self, **kwargs):
        context = super(ArticleDetailView, self).get_context_data(**kwargs)
        return context
like image 926
Erik Åsland Avatar asked Jan 08 '23 02:01

Erik Åsland


1 Answers

The super method will access to the current class and call an specific method, in this case:

super(ArticleDetailView, self)  # Access to the current class

And execute an specific method:

.get_context_data(**kwargs)

The .get_context_data() method in a View class, returns the context passed to the template (.html file). In this case, you're using a DetailView, so you have some predefined context, such as: object or article.

If you just override .get_context_data() without calling .super(), like this:

def get_context_data(self, **kwargs):
    my_context = {...}
    return my_context

You will lost the predefined variables in the DetailView context. But if you want to add some new variables (values) to the current DetailView's context, you need the original context, and that's what super(ArticleDetailView, self).get_context_data(**kwargs) will give you. So you will use it in this way:

def get_context_data(self, **kwargs):
    context = super(ArticleDetailView, self).get_context_data(**kwargs)
    context.update({'my_key': 'my_value'})
    return context

Now you will be able to use your own value in the template without losing the default DetailView's context values.

like image 173
Gocht Avatar answered Jan 18 '23 06:01

Gocht