I added mydata in setup function of the BaseView.
class BaseView(View): def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.mydata = table.objects.all()
When I print it in the get function of child class, the value is correct but I'd like this variable be added in template file automatically.
def get(self, request, pk=''): print('self.active_apps in plan') print(self.active_apps) user_info = request.session.get('user_info') context = {'user_info':user_info} if pk != '': item = get_object_or_404(self.model_class, pk=pk) form = self.form_class(instance=item) context['form'] = form context['pk'] = pk else: form = self.form_class() context['form'] = form return render(request, self.template_name, context)
What you are looking for is probably not adding this in views, but a context processor [Django-doc].
We can define such context processor like:
and then register the context processor in the
settings.py:This will, each time you render a template with this backend, run the context processors to populate the context further.
Since querysets are lazy, it will also not make an requests if the template does not "consume" the
my_data. But now if we thus render a template, we can enumerate overmy_data.