how generic view works in django?

89 views Asked by At

I want to using generic classes for my blog. Everything is fine and I know how it works and I like the idea behind it. But I see a generic class just grabs one or few blog posts and sends them to template. Is it possible to add more data to template with generic class view? Like in blog index page I will have recently 5 posted article. Also I want to send a poll to same template. Is this possible with generic class view? if yes (it should be), what part of django documentation should I read?

Update: look at this code(from django documentation):

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

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

The above code sends latest 5 polls to polls/index.html. If I want to send some extra data or information to same template to show to user. like latest news in side pannel. But there is no place in generic class view to add the news. The index view class designed to show just list of latest polls. nothing else.

1

There are 1 answers

1
Zagorodniy Olexiy On

You can use get_context_data. Here is example how I use 2 apps in 1 view.

class MainPageView(ListView):
    model = MainPaige
    template_name = 'main/index.html'

    def get_context_data(self, **kwargs):
            ctx = super(MainPageView, self).get_context_data(**kwargs)
            ctx['main_page'] = MainPaige.objects.all()
            ctx['main_news'] = News.objects.order_by('-pub_date') [:5]
            return ctx