How to Pass Variable to the Template Class Based View
Aug. 22, 2022
django
Simple example how to pass a variable to the class based view template context in Django.
class SomeView(TemplateView):
template_name = 'template_name.html'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
some_valiable = 'value'
context['some_valiable'] = some_valiable
return context
It also could be a queryset
class SomeView(TemplateView):
template_name = 'template_name.html'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
comments = Comment.objects.filter(post_id=self.kwargs['post_id'])
context['comments'] = comments
return context
Then it can be looped in the template
{% for comment in comments %}
{{ comment.text }}
{% endfor %}