【问题标题】:Refer to multiple Models in View/Template in Django在Django的视图/模板中引用多个模型
【发布时间】:2013-08-24 13:55:55
【问题描述】:

我正在使用 Python/Django 迈出第一步,并在一个 Django 项目中编写了一个包含多个 Django 应用程序的示例应用程序。现在我添加了另一个名为“仪表板”的应用程序,我想在其中显示来自不同应用程序的数据。目前我仍然使用这个简单的基于类的通用视图,它在仪表板上显示了我的小联系人-App 的条目:

views.py:

from django.views.generic import ListView
from contacts.models import Contact

class ListDashboardView(ListView):
     model = Contact
     template_name = 'dashboard.html'

urls.py:

url(r'^$', dashboard.views.ListDashboardView.as_view(),
    name='dashboard-list',),

在dashboard.html 中我这样做:

<ul>
  {% for contact in object_list %}
    <li class="contact">{{ contact }}</li>
  {% endfor %}
</ul>

谁能向初学者解释如何在我的模板中访问多个模型?我不仅想显示我的“联系人”应用程序中的联系人,还想显示其他应用程序的数据,例如我的“库存”应用程序和第三个应用程序。

我知道,我必须导入它:

from inventory.models import Asset
from polls.models import Poll

但是要使用视图将所有这些数据传递到我的单个模板,必须做些什么呢?以及如何在我的模板中访问这些数据?

解决方案可能在Django Pass Multiple Models to one Template,但我必须承认我并不真正理解它。

【问题讨论】:

    标签: python django templates django-models


    【解决方案1】:

    您需要覆盖get_context_data 方法并在上下文中传递您想要的任何内容:

    class ListDashboardView(ListView):
        model = Contact
        template_name = 'dashboard.html'
    
        def get_context_data(self, **kwargs):
            ctx = super(ListDashboardView, self).get_context_data(**kwargs)
            ctx['polls'] = Poll.objects.all()
            return ctx
    

    【讨论】:

      【解决方案2】:

      添加到阿米尔的答案

      在你会做的 html 中:

      {% for contact in object_list %}
      <li>{{contact.object}}</li>
      {% endfor %}
      

      引用“联系人”模型对象

      {% for x in polls %}
      <li>{{ x.object }}</li>
      {% endfor %}
      

      引用“投票”模型对象

      (起初这对我来说并不直观)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-26
        • 1970-01-01
        • 2018-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        相关资源
        最近更新 更多