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'),
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With