Colton Allen
Colton Allen

Reputation: 3060

Passing a Query Set to a Template

I have a template that lists out all of the projects that have been created. I've used the models.Manager to create a query set that counts the number of tasks a particular project has. I've also created two variables in views.py that filter the results to provide more specific output. Within my template I want to be able to display Project X has 11 tasks open and Project Y has 5 tasks open (in a tabular format).

It should be noted that I can access the TaskCount manager's result by using {{ project.tasks }} but what I'm really interested in is accessing the open_set variable in my template.

models.py

class TaskCount(models.Manager):
    def get_query_set(self):
        return super(TaskCount, self).get_query_set().annotate(tasks=Count('task'))

class Project(models.Model):
    # Model Fields
    # some fields
    # Model Managers
    with_tasks = TaskCount()

views.py

class ListProject(ListView):
    model = Project
    template_name = 'list_project.html'
    # Queries
    open_set = Project.with_tasks.filter(task__status=0)
    closed_set = Project.with_tasks.filter(task__status=1)

list_project.html

{% for project in object_list %}
    <tr>
        <!-- works -->
        <td><a href="{{ project.get_absolute_url }}">{{ project.name }}</a></td>
        <!-- works -->
        <td>{{ project.created_by }}</td>
        <!-- doesn't work -->
        <td>{{ open_set }}</td>
        <!-- doesn't work -->
        <td>{{ project.closed_set }}</td>
    </tr>
{% endfor %}

Upvotes: 0

Views: 95

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

You shouldn't put those queries there at the class level: the ListView doesn't know about them and won't pass them anywhere. Instead you should override get_context_data and return them from there.

class ListProject(ListView):
    ...
    def get_context_data(self, *args, **kwargs):
        context = super(ListProject, self).get_context_data(*args, **kwargs)
        context['open_set'] = Project.with_tasks.filter(task__status=0)
        context['closed_set'] = Project.with_tasks.filter(task__status=1)
        return context

Upvotes: 1

Related Questions