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

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!

Struggle with the Django Documentation?

If this post helped you, sign up for my newsletter and you'll get a new post each week that will help you master Django ABSOLUTELY FREE!

Powered by ConvertKit