如何在同一个d上使用Django for循环两次

2024-03-29 09:06:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用for循环在同一Django模板中对同一数据进行两次迭代。但是,第二个for循环只返回数据库中的第一个对象。你知道吗

基本上,我有一个在主页上的数据库中的每项工作的图像,当点击它应该显示一个更详细的工作说明。数据库中的所有作业在主页上都显示得很好,但单击时都显示第一个作业的描述。你知道吗

我认为这与只能使用一次迭代器有关,但我不知道解决方案是什么。你知道吗

你知道吗型号.py你知道吗

from django.db import models

class Job(models.Model):
    title = models.CharField(max_length=50, default="Example Work")
    image = models.ImageField(upload_to='images/')
    summary = models.TextField()

你知道吗视图.py你知道吗

from django.shortcuts import render
from .models import Job

def get_index(request):
    jobs = Job.objects
    return render(request, 'index.html', {'jobs': jobs})

你知道吗索引.html你知道吗

{% for job in jobs.all %} <div class="col-md-6 col-lg-4"> <a class="portfolio-item d-block mx-auto" href="#portfolio-modal"> <div class="portfolio-item-caption d-flex position-absolute h-100 w-100"> <div class="portfolio-item-caption-content my-auto w-100 text-center text-white"> <i class="fas fa-search-plus fa-3x"></i> </div> </div> <img class="img-fluid" src="{{ job.image.url }}" alt=""> </a> <h3 class="text-center text-secondary">{{ job.title }}</h3> </div> {% endfor %} <!-- Portfolio Modal --> {% for job in jobs.all %} <div class="portfolio-modal mfp-hide" id="portfolio-modal"> <div class="portfolio-modal-dialog bg-white"> <a class="close-button d-none d-md-block portfolio-modal-dismiss" href="#"> <i class="fa fa-3x fa-times"></i> </a> <div class="container text-center"> <div class="row"> <div class="col-lg-8 mx-auto"> <h2 class="text-secondary text-uppercase mb-0">{{ job.title }}</h2> <hr class="star-dark mb-5"> <img class="img-fluid mb-5" src="{{ job.image.url }}" alt="Image of website"> <p class="mb-5">{{ job.summary }}</p> <a class="btn btn-primary btn-lg rounded-pill portfolio-modal-dismiss" href="#"> <i class="fa fa-close"></i>Close Project</a> </div> </div> </div> </div> </div> {% endfor %}

只是为了上下文,我从中删除了很多html代码索引.html因为这一切都很好,可能并不相关。我在一个循环内尝试过,但也不起作用。描述将在同一页上的新窗口中打开。我试过任何我能想到的方法,但都没有成功。仍在掌握Django和Python。谢谢你的帮助。你知道吗


Tags: textfromdiv数据库imgformodelshtml
1条回答
网友
1楼 · 发布于 2024-03-29 09:06:38

这与Django为每个迭代输出相同的数据无关。如果您在浏览器中通过View Source检查生成的HTML,您肯定会看到正确的数据。你知道吗

问题在于HTML本身。不能有多个元素具有相同的HTML id属性;但每个元素都使用id="portfolio-modal"。当你的JS试图弹出模态时,它只会找到这个ID的第一个实例

您需要在每次迭代中使用不同的ID—可能是通过附加一个唯一的元素,例如Job pk—和/或使用一个类来触发模式。你知道吗

相关问题 更多 >