2017-01-16 76 views
3

我有一個模板,我需要從多個模型呈現信息。我的models.py是這個樣子:Django模板與多個模型

# models.py 
from django.db import models 

class foo(models.Model): 
    ''' Foo content ''' 

class bar(models.Model): 
    ''' Bar content ''' 

我也有一個文件views.py,從中我根據this Django documentationthe answer given here寫道,看起來是這樣的:

# views.py 
from django.views.generic import ListView 
from app.models import * 

class MyView(ListView): 
    context_object_name = 'name' 
    template_name = 'page/path.html' 
    queryset = foo.objects.all() 

    def get_context_data(self, **kwargs): 
     context = super(MyView, self).get_context_data(**kwargs) 
     context['bar'] = bar.objects.all() 

     return context 

和我在urls.py urlpatterns的有以下對象:

url(r'^path$',views.MyView.as_view(), name = 'name'), 

我的問題是,在模板頁/ path.html我怎麼可以參考的對象,並從F中的對象屬性oo和bar將它們顯示在我的頁面中?

回答

1

要從模板訪問FOOS,你必須包括它在上下文:

# views.py 
from django.views.generic import ListView 
from app.models import * 
class MyView(ListView): 
    context_object_name = 'name' 
    template_name = 'page/path.html' 
    queryset = foo.objects.all() 

    def get_context_data(self, **kwargs): 
     context = super(MyView, self).get_context_data(**kwargs) 
     context['bars'] = bar.objects.all() 
     context['foos'] = self.queryset 
     return context 

現在,在您的模板,你可以通過引用您在創建中get_context_data上下文字典時使用的密鑰訪問值:

<html> 
<head> 
    <title>My pathpage!</title> 
</head> 
<body> 
    <h1>Foos!</h1> 
    <ul> 
{% for foo in foos %} 
    <li>{{ foo.property1 }}</li> 
{% endfor %} 
    </ul> 

    <h1>Bars!</h1> 
    <ul> 
{% for bar in bars %} 
    <li>{{ bar.property1 }}</li> 
{% endfor %} 
    </ul> 
</body> 
</html> 
-1

對於最簡單的情況下,只需使用普通的Django模板語言結構,forloop - 標籤和{{}}變量符號:

{% for b in bar %} # should be called 'bars' in the context, really 
    {{ b }}   # will render str(b) 
    {{ b.id }}   # properties, fields 
    {{ b.get_stuff }} # callables without parentheses 
{% endfor %} 

更多請見template language docs