【问题标题】:Django template with multiple models具有多个模型的 Django 模板
【发布时间】:2017-05-31 16:08:42
【问题描述】:

我有一个模板,我需要从中呈现来自多个模型的信息。我的 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 documentationthe 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 中的对象和对象属性以在我的页面中显示它们?

【问题讨论】:

    标签: python django django-templates jinja2


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      对于最简单的情况,只需使用常见的 django 模板语言结构,forloop-tag 和 {{}} 变量表示法:

      {% for b in bar %}   # should be called 'bars' in the context, really
        {{ b }}            # will render str(b)
        {{ b.id }}         # properties, fields
        {{ b.get_stuff }}  # callables without parentheses
      {% endfor %}
      

      请参阅template language docs 了解更多信息。

      【讨论】:

        猜你喜欢
        • 2014-05-20
        • 2016-11-06
        • 2020-04-05
        • 2020-06-06
        • 2021-01-29
        • 1970-01-01
        • 2012-03-16
        • 2017-08-07
        • 2016-11-17
        相关资源
        最近更新 更多