How to Pass Additional Variables in Template when using Django Generic Views

Posted by Chris Bartos on April 12, 2016

We’ve all done this before. We learn about class-based Generic Views in Django and we want to use them immediately in our code. Without reading all the way through the documentation, you make the switch.

Suddenly, you’re not really sure how to add additional data to your templates. Maybe class-based Generic Views aren’t really what they were cracked up to be?!

You’re trying to create a Generic View that lists all the tags available for your blog. However, maybe you want to list the tags in the same place as all your posts.

In a fit of rage, maybe you’ve tried to code the following:

class BlogIndex(ListView):
    queryset = Post.objects.published()
    template_name = "index.html"

    def get_tags():
        tags = Tag.objects.all()
        return tags

You’re thinking this will allow you to call the function to get the tags inside of a template using something like {% for tag in view.get_tags %}.

There are reasons why you might want to do it this way. However, if you’re just interested in adding data to your view’s context data this is the correct way to do it.

The way you pass additional data to your template using Django Class-based Views is by implementing your own implementation of the get_context_data method

For example, let’s use the example above with adding Tags to your template.

class BlogIndex(ListView):
    queryset = Post.objects.published()
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super(BlogIndex, self).get_context_data(**kwargs)
        context['tags'] = Tag.objects.all()
        return context

The new version of BlogIndex will allow you to access your tags using {{ tags }}

Try this simple way of updating your Generic View context dict and you’ll be amazed at how simple Generic Views are to use!

Need help with Django REST Framework? Django REST Framework documentation a little confusing?

Join me for my FREE Django REST Framework email course:

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days.
You'll learn:

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • JQuery Integration
  • AngularJS Integration
Powered by ConvertKit