Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - DetailView how to display two models at same time

Tags:

python

django

I have two models : Advertisment and Banner

when I using "generic view" DetailView How can I Bring two models at the same time The code below bring only one Advertisment

My url.py

url(r'^(?P<pk>\d+)/$', DetailView.as_view(
    model               = Advertisment,
    context_object_name = 'advertisment',
), name='cars-advertisment-detail'),
like image 472
creative creative Avatar asked Feb 18 '13 12:02

creative creative


2 Answers

Sure, just override get_context_data to add stuff to the context.

path('<int:pk>/', YourDetailView.as_view(), name='cars-advertisment-detail'),

class YourDetailView(DetailView):
    context_object_name = 'advertisment'
    model = Advertisement

    def get_context_data(self, **kwargs):
        """
        This has been overridden to add `car` to the template context,
        now you can use {{ car }} within the template
        """
        context = super().get_context_data(**kwargs)
        context['car'] = Car.objects.get(registration='DK52 WLG')
        return context
like image 183
Matt Deacalion Avatar answered Nov 15 '22 04:11

Matt Deacalion


For me, it's easier to make a custom mixin like this:

class ExtraContextMixin(object):

    def get_context_data(self, **kwargs):
        context = super(ExtraContextMixin, self).get_context_data(**kwargs)
        context.update(self.extra())
        return context

    def extra(self):
        return dict()

Later you can just subclass this mixin and then override the extra like this:

class MyDetailView(ExtraContextMixin, DetailView):

    def extra(self):
        extra = Extra.objects.all()
        return dict(extra = extra)

I think this is cleaner rather than overriding get_context_data

like image 23
Otskimanot Sqilal Avatar answered Nov 15 '22 03:11

Otskimanot Sqilal