【问题标题】:Django passing multiple models to a templateDjango将多个模型传递给模板
【发布时间】:2016-11-17 22:32:51
【问题描述】:

我是第一次开发 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(), ),
]

【问题讨论】:

  • “将多个模型传递给模板”是什么意思?
  • 我需要使用 Episode 模型来索引模板。

标签: python django templates model


【解决方案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

然后在您的模板中将有一个带有情节模型对象的{{ episode_objects }} 变量。

【讨论】:

  • 这就是我想要的。谢谢!
  • @Crownstyle 如果您觉得这很有帮助,请考虑接受此答案以帮助遇到同样问题的其他人。
猜你喜欢
  • 2012-08-24
  • 2012-09-27
  • 2023-03-07
  • 2016-02-15
  • 2021-06-05
  • 2017-09-03
  • 2016-07-08
  • 1970-01-01
  • 2019-04-03
相关资源
最近更新 更多