【问题标题】:Django: Using a For Loop in a DetailView class pageDjango:在 DetailView 类页面中使用 For 循环
【发布时间】:2021-02-09 01:32:45
【问题描述】:

使用 Django,是否可以在 DetailView 类页面的页面中使用 For 循环?

我有从我的数据库中提取的东西的详细信息页面,但我希望我可以在该页面内有一个 For 循环,该循环遍历该表中的名称列表以相互链接(如果这有意义的话)。

urls.py:

from django.urls import path, include
from .views import payplan_emails_view

urlpatterns = [
    path('normal-payplan-emails/<int:pk>', payplan_emails_view.as_view(), name="normal-payplan-emails"),
]

views.py:

from django.shortcuts import render, redirect
from .models import knowledgebase_instruction
from django.views.generic import DetailView


class payplan_emails_view(DetailView):
    model = knowledgebase_instruction
    template_name = "instructions/payplans_base.html"

payplans_base.html:

{% block content %}

<h4>{{knowledgebase_instruction.name}}</h4>
<p>{{knowledgebase_instruction.instructions|safe}}</p>
              
<ul>

  <!-- I would love to loop through items in the table here -->
  
  <li><a href="#">List Item 1</a></li>
</ul>

{% endblock%}

【问题讨论】:

  • 我认为你不能在 DetailView 中使用for loop,因为它返回单个对象。

标签: python django django-views django-templates


【解决方案1】:
{% for o in some_list %}
    <tr>
       {{ o }}
    </tr>
{% endfor %}

详情请参考:Django documentation

【讨论】:

    【解决方案2】:

    如果我理解您的问题,您必须创建新类 ListView 并将其放在同一个模板中。

    观看次数:

    from django.views.generic import ListView
    
    class list_name(ListView):
      model = model_in_what_are_users_stored
      template_name = "instructions/payplans_base.html"
    

    模板:

    {% for model_in_what_are_users_stored in model_in_what_are_users_storeds %}
    { model_in_what_are_users_stored.user }
    {% endfor %}
    

    【讨论】:

    • 那我需要在 urls.py 中注册一个新的 URL,对吧?我不认为(或者至少,我不知道如何,大声笑)我可以拥有一个有两个视图的页面......所以你在查看特定主键的详细信息页面上,同时遍历 ListView在同一页面上查看。
    【解决方案3】:

    我走了一条不同的路。

    而不是使用通用的 DetailView。我刚刚在视图中创建了一个新函数并在其中查询数据库,从 URL 中传入 pk。

    现在效果很好。

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 1970-01-01
      • 2020-01-29
      • 2015-09-22
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多