1

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?

Xeen
  • 6,955
  • 16
  • 60
  • 111

3 Answers3

5

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
Community
  • 1
  • 1
Héléna
  • 1,075
  • 3
  • 14
  • 39
4

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.

Brahm
  • 3
  • 3
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • Okay thank you for that answer, but now it throws out an error `PageView is missing a queryset. Define PageView.model, PageView.queryset, or override PageView.get_queryset().`, can you please show me some kind of a manual or smthn how to handle this, because google doesn't find that kind of an error .. – Xeen Oct 15 '13 at 14:05
  • Hmm. I suspect you need to add a queryset property to your PageView class of: `queryset = Page.objects.all()` – Brandon Taylor Oct 15 '13 at 14:12
0

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