Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django view: get_context_data() vs get()

We can do this in Django:

class LoginView(generic.FormView):

    def get_context_data(self, **kwargs):
        common = CommonView(self, **kwargs)
        context = super(LoginView, self).get_context_data(**kwargs)
        context['common'] = common.infos

or:

class LoginView(generic.FormView):

    def get(self, request, *args, **kwargs):
        common = CommonView(self, **kwargs)
        return render(request, self.template_name, {'common': common.infos })

Which one is better and why?

like image 516
Olivier Pons Avatar asked Mar 06 '16 08:03

Olivier Pons


2 Answers

Using get_context_data() is interesting since it has only one goal (do one thing and do it well): pass data to the template.

On the other hand, get() has many tasks to do in order to return an HttpResponse in the end. get() should rather be a skeleton of method calls, delegating tasks. Among them, you have get_context_data(), and others according to the class you are inheriting.

As long as it is possible, I think it is better to let the parent class(es) handle the get(), post(), ... methods and use the convenience methods they provide.

As far as I'm concerned, the only case for which I had to handle the get() method myself is when writing generic views.

like image 116
Antoine Pinsard Avatar answered Sep 22 '22 13:09

Antoine Pinsard


None of them is "better". I'd say it depends on the scenario what you need to do. get_context_data() is called for all the request methods (post, get), so if you need to have there some data available every time, use get_context_data(). If you need the data only for a specific request method (eg. in get), then put it in get.

like image 21
yedpodtrzitko Avatar answered Sep 19 '22 13:09

yedpodtrzitko