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!

What do you do after the Official Django Tutorial?

Here's what you'll learn:

  1. Start writing tests
  2. Increase the size / complexity of the Polls application.
  3. Learn how to code in Django by reading the Django source code.
  4. Finding code snippets to use in your website by reading the code of other websites.
  5. Using Javascript in a web app.
  6. Deploying on Heroku and AWS.
We won't send you spam. Unsubscribe at any time. Powered by ConvertKit


Get some value from this post? Please like and share this post because more people also deserve some value. :-)