2016-07-14 56 views
0

我正在開發第一次使用Django應用程序。我怎麼能傳遞多個模型模板Django將多個模型傳遞給模板

views.py

from django.views.generic import ListView, DetailView 
from django.utils import timezone 
from LastAlly.models import Article, Episode 


class IndexView(ListView): 
    queryset = Article.objects.all().order_by("-date")[:3] 
    template_name = 'index.html' 

urls.py

from django.conf.urls import url, include 
from django.contrib import admin 
from django.views.generic import ListView, DetailView 
from LastAlly.views import IndexView 

urlpatterns = [ 
    url(r'^$', IndexView.as_view(),), 
] 
+1

「將多個模型傳遞給模板」是什麼意思? – Gocht

+0

我需要使用Episode模型來索引模板。 – Crownstyle

回答

1

您可以編輯視圖的方法,在這種情況下,你可以編輯.get_context_data()方法:

class IndexView(ListView): 
    queryset = Article.objects.all().order_by("-date")[:3] 
    template_name = 'index.html' 

    def get_context_data(self, *args, **kwargs): 
     context = super(IndexView, self).get_context_data(*args, **kwargs) 
     context['episode_objects'] = Episode.objects..... 
     return context 

然後在你的模板將與T A {{ episode_objects }}變量他插播模型對象。

+0

這就是我想要的。謝謝! – Crownstyle

+0

@Crownstyle如果您認爲此內容有幫助,請考慮接受此答案以幫助其他人解決同一問題。 – Gocht