python - 具有多个模型的 Django 模板

标签 python django django-templates jinja2

我有一个模板,我需要从中呈现来自多个模型的信息。我的 models.py 看起来像这样:

# models.py
from django.db import models

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

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

我还有一个文件views.py,我根据this Django documentation写的和 the 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'),

我的问题是,在模板 page/path.html 上,如何从 foo 和 bar 引用对象和对象属性以在我的页面中显示它们?

最佳答案

要从您的模板访问 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>

关于python - 具有多个模型的 Django 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682846/

相关文章:

python - Heroku 上的错误请求 400 Django 应用程序

python - 建议一种在单击按钮时填充数据库的方法

django - 如何将属性 '_meta' 添加到对象?

python - 运行时错误 : Graph ops missing from the python registry ( {'SentencepieceEncodeSparse' }) are also absent from the c++ registry

python - 以 BFS 风格将深度的嵌套字典(森林)写入文本文件

python - 即使扩展了模板,为什么还要为每个模板加载静态文件?

Python服务器 "Only one usage of each socket address is normally permitted"

Django 到 PostgreSQL : Error loading psycopg2

python - 没有名为索引的模块

django - Google map 无法在 App Engine 开发服务器上的 Django 模板中运行