gglasses gglasses - 5 months ago 35x
Python Question

Django: ListView. Where can I declare variables that I want to have on template?

One of my tables in my app is called

and I have the following class to list all of the objects on that table:

from django.views.generic import ListView
from galleries.models import Gallery

class GalleryList(ListView):
template_name = "path/to/template"
context_object_name = "object_list"

def queryset(self):
return Gallery.objects.order_by('-title')[:20]

And it does the job. On my template I do the following:

{% block gallery_list %}
<h1>Gallery List</h1>
{% for gallery in object_list %}
<li><img src="{{ gallery.thumbnail.url }}" />{{ gallery.title }}</li>
{% endfor %}
{% endblock %}

Everything works as expected. The thing here is that on my
template I have
{% block title %}
for the
meta title
{% block description %}
for my
meta description
tag in the header. And I want to be able to declare it somewhere and pass it to the view. To be clear, the variables
are strings (ex:
title="List of all galleries on website"

On the view I want to do something like:

{% extends "base.html" %}

{% block title %}{{ title }}{% endblock %}
{% block description %}{{ description|default:title }}{% endblock %}

But, on the class
I don't know where to declare the variables
. I don't know if that's possible or proper for Django. I want to do what's right.

Also, as I have a costume template for listing all the galleries I could just do:

{% extends "base.html" %}

{% block title %}List of all galleries on website{% endblock %}
{% block description %}List of all galleries on website...{% endblock %}

But then again, I don't know if that's proper for a well coded Django app. I'm a beginner with Django and I would like to know what's the way to go about this. Hope my question is clear enough.


You can override the ListViews get_context_data method to add whatever additional context variables to you want to the context:

class GalleryList(ListView):

    def get_context_data(self, **kwargs):
        ctx = super(GalleryList, self).get_context_data(**kwargs)
        ctx['title'] = 'My Title'
        ctx['description'] = 'My Description'
        return ctx

The other approach - of having a template that fills in this information - is also sound. Which is better really depends on how dynamic the data is. If the title/description is based on model data or some other factors, then it makes sense to set it in the view. If it is fixed for a particular template then it is probably cleaner to put in in a template that extends base.html.