jramm
jramm

Reputation: 6655

Django DetailView - get all objects?

I have a subclass of DetailView to show details on a single object (obv). I also have a subclass of ListView which provides the homepage (with some info on all projects)

But now I want to include a sidebar in my base template so that all pages will have links to each view provided by DetailView.

How can I do this in a way such that I can access all objects in the template provided by DetailView ?

Upvotes: 1

Views: 867

Answers (2)

Adrian Ghiuta
Adrian Ghiuta

Reputation: 1619

A couple of DRY methods:

  1. Have all your DetailViews inherit from a base DetailView that uses get_context_data to retrieve the objects and adds them to the context

  2. Write a custom template tag and use it in your base template

Upvotes: 0

madzohan
madzohan

Reputation: 11808

class YourDetailView(DetailView):
    # ...

    def get_context_data(self, **kwargs):
        context = super(YourDetailView, self).get_context_data(**kwargs)
        context['all_objects'] = YourModel.objects.all()

        return context

https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_data

Upvotes: 1

Related Questions