2013-10-15 130 views
0

我正在开发一个wiki页面这基本上奠定了像这样:如何在Django的一个模板中使用多个模型?

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 

我希望做的是当我点击页面或类别,看元素的部件安装什么(例如,当我点击一个页面时,类别和类别项目列表),但就我对Django知识的了解而言,这需要我在单个模板上使用两个模型。

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

这是我对“查看页面”的看法部分,当我尝试使用两个模型时,它崩溃了。我能做些什么来使用多个模型?

回答

2

您需要在您的基于类视图覆盖get_context_data

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

这将允许您根据需要添加尽可能多的上下文变量。

+0

好的谢谢你这个问题的答案,但现在它抛出一个错误'浏览量缺少一个查询集。定义PageView.model,PageView.queryset或重写PageView.get_queryset()。',请给我看一些手册,或者告诉我如何处理这个问题,因为谷歌没有发现那种错误。 – Xeen

+0

嗯。我怀疑你需要为你的PageView类添加一个queryset属性:'queryset = Page.objects.all()' – Brandon

0

考虑为页面中使用的每个链接提供唯一的URL。 由此您可以使用不同的视图与差异模型。

1

我在下面的链接了一个例子: 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 
相关问题