Issue
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)
Solution
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:
# my_app/context_processors.py
def table_data(request):
return {'my_data': table.objects.all()}
and then register the context processor in the settings.py
:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
# …,
'context_processors': [
# …,
'my_app.context_processors.table_data'
]
},
}
]
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 over my_data
.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.