~ / blog / qa / how-to-pass-variable-to-the-template-class-based-view
django 2022-08-22ยท1 min read

How to Pass Variable to the Template Class Based View

Simple example how to pass a variable to the class based view template context in Django.

python
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

python
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

python
{% for comment in comments %}
    {{ comment.text }}
{% endfor %}