11

As a Django beginner I'm working on the the tutorial provided by django docs at https://docs.djangoproject.com/en/1.5/intro/tutorial04/

In it they demonstrate a list of multiple polls that are listed using a query by publication date. Could I add another list to be also used in the template to be used as well. Example Displaying a list of latest polls by date and another by alphabetical order on the same page.

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        """Return the last five published polls."""
        return Poll.objects.order_by('-pub_date')[:5]

1 Answer 1

15

Absolutely, you'll just need to write your own 'get_context_data' method that will retrieve those values and then they will be available in the view. Something like:

def get_context_data(self, *args, **kwargs):
    context = super(IndexView, self).get_context_data(*args, **kwargs)
    context['alphabetical_poll_list'] = Poll.objects.order_by('name')[:5]
    return context 

With this both {{ latest_poll_list }} and {{ alphabetical_poll_list }} would be available in your template.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to note that this appends variables to the template context, so the original get_queryset and context_object_name should be maintained in the original IndexView

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.