Xeen
Xeen

Reputation: 7003

How to use multiple models in one template in Django?

I'm developing a wiki page that's basically laid out like so:

1. Page
    Page ID
    Page name
    Has many: Categories

2. Category
    Category ID
    H2 title
    Has many: category items
    Belongs to: Page

3. Category item
    Category item ID
    H3 title
    Body text
    Image
    Belongs to: Category

What I'd like to do is when I click on a Page or a Category, to see what parts of the element are attached to it (list of categories and category items when I click on a page, for example), but as far as I've got in to my Django knowledge, this requires me to use two models on a single template.

class PageView(DetailView):
    model = Page
    template_name = 'page.html'

This is what my view part for the "View page" looks like, when I try to use two models, it crashes. What can I do to use more than one model?

Upvotes: 1

Views: 6714

Answers (3)

Brandon Taylor
Brandon Taylor

Reputation: 34553

You need to override get_context_data on your class based view: #EDIT changed period to comma after self

    def get_context_data(self, **kwargs):
        context = super(PageView, self).get_context_data(**kwargs)
        context['more_model_objects'] = YourModel.objects.all()
        return context

This will allow you to add as many context variables as you need.

Upvotes: 4

Héléna
Héléna

Reputation: 1095

I got an example in the following link: Django Pass Multiple Models to one Template

class IndexView(ListView):
context_object_name = 'home_list'    
template_name = 'contacts/index.html'
queryset = Individual.objects.all()

def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['roles'] = Role.objects.all()
    context['venue_list'] = Venue.objects.all()
    context['festival_list'] = Festival.objects.all()
    # And so on for more models
    return context

Upvotes: 5

user2873552
user2873552

Reputation: 51

Think about giving unique urls for each link used in the page. BY this you can use different views with diff models.

Upvotes: 0

Related Questions