Multiple template templates for common templates

What is the SIMPLEST method for including two models in a common IndexView? My two models are CharacterSeries

and CharacterUniverse

.

My views.py

    from .models import CharacterSeries, CharacterUniverse


    class IndexView(generic.ListView):
        template_name = 'character/index.html'
        context_object_name = 'character_series_list'

        def get_queryset(self):
            return CharacterSeries.objects.order_by('name')


    class IndexView(generic.ListView):
        template_name = 'character/index.html'
        context_object_name = 'character_universe_list'

        def get_queryset(self):
            return CharacterUniverse.objects.order_by('name')

      

I need to know the shortest and most elegant code. Looked a lot but don't want to use mixins. Maybe I'm not being pointed in the right direction.

Thanks everyone.

+3


source to share


2 answers


You can pass one request in context to the ListView like this,



class IndexView(generic.ListView):
    template_name = 'character/index.html'
    context_object_name = 'character_series_list'
    model = CharacterSeries

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context.update({
            'character_universe_list': CharacterUniverse.objects.order_by('name'),
            'more_context': Model.objects.all(),
        })
        return context

    def get_queryset(self):
        return CharacterSeries.objects.order_by('name')

      

+10


source


https://docs.djangoproject.com/en/1.8/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data

Sounds like the mixin is the only one (right)? way. I added a method get_context_data

and now it works.

A quick question about adding more than two models ..?



below works with two models:

class IndexView(generic.ListView):
    template_name = 'character/index.html'
    context_object_name = 'character_series_list'

    def get_queryset(self):
        return CharacterSeries.objects.order_by('name')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['character_universe_list'] = CharacterUniverse.objects.order_by('name')
        return context

      

+4


source







All Articles