【问题标题】:Having two Generic ListViews on the same page在同一页面上有两个通用 ListView
【发布时间】:2023-03-25 07:28:02
【问题描述】:

目前可以在活动下显示对象列表,但采访仍然是空的(尽管有与采访对象数量相对应的项目符号 - 只是没有显示文本)。

views.py:

class IndexView(generic.ListView):
  template_name = 'expcore/index.html'
  model = Activity
  context_object_name = 'activities_list'
  queryset = Activity.objects.all()

  def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['interviews_list'] = Interview.objects.all()
    return context

index.html:

  <div>
<h1>Activities</h1>
<ul>
{% for activity in activities_list %}
    <li><a href='/activity/{{ activity.name }}'></a></li>
{% empty %}
    <li>No activities available yet.</li>
{% endfor %}
</ul>
</div>

<div>
<h1>Interviews</h1>
<ul>
{% for interview in interviews_list %}
    <li><a href='/interview/{{ interview }}'>{{ interview.name }}</a></li>
{% empty %}
    <li>No interviews available yet.</li>
{% endfor %}
</ul>
</div>

任何想法为什么没有显示采访对象?

【问题讨论】:

  • @IsaBek 谢谢你的回复。我对 Python/Django 完全陌生,我很难将其他人的代码适应我自己的代码。能否提供一些示例代码?
  • 这真的是最好的学习方式。如果你只是复制粘贴,你将无法调试自己的代码。

标签: python django listview


【解决方案1】:

覆盖IndexView 中的get_context_data 函数。在那里您可以发送多个对象。

class IndexView(generic.ListView):
  template_name = 'expcore/index.html'
  model = Activity
  context_object_name = 'activities_list'
  queryset = Activity.objects.all()

  def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['interviews_list'] = Interview.objects.all()
    return context

在模板上你可以这样做。

活动

{% for activity in activities_list %}
{% endfor %}

面试

{% for interview in interviews_list %}
{% endfor %}

【讨论】:

  • 现在正在显示活动列表,但在采访下仍然没有任何内容(即使在采访下有项目符号 - 只是没有显示采访的名称)。您对为什么会这样有任何想法吗?
  • 你能展示你的 IndexView 和打印采访的代码吗?
  • 您确定覆盖IndexView 中的get_context_data 函数吗?我的意思是get_context_dataIndexView 下。
猜你喜欢
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多