python - Django 将多个模型传递给模板

标签 python django templates model

我第一次开发 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/

相关文章:

javascript - Python Selenium 访问 javascript 菜单中的隐藏链接

python - 交互式 Jupyter 小部件在 Jupyter Lab 中不起作用

django - pip install django --upgrade 安装旧版本

c++ - 我可以访问变量的类型以进行泛型编程吗?

C++ 嵌入式模板模板

c++ - 不能在从 std::vector 继承的类中使用 typedef 迭代器

python - MSSQL 'Numeric Value Out of Range' 20 位 python Long Int 到 Numeric(24,0) 列时出错

python初学者: can't init an object from zero

python - 通过 Django 中的 View 提供静态文件

python - 如何将 Docker 添加到 Django + Gunicorn + Nginx + Fabric