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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With