我第一次开发 Django 应用程序。如何将多个模型传递给模板
View .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'
url.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(), ),
]
最佳答案
您可以编辑 View 的方法,在本例中您可以编辑 .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
然后在您的模板中将有一个包含 Episode 模型对象的 {{ Episode_objects }}
变量。
关于python - Django 将多个模型传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38383836/