如何在另一个内部使用HTML变量

时间:2018-09-30 12:35:51

标签: html django

我有一段代码循环通过某些对象。我还有另一组对象也要遍历。有没有一种方法可以使用for loop.counter增加图像对象?

    <div class="row">
        {% for project in projects.all %}
            <div class="col-md-4 col-sm-6">
                <div class="news-section-single">
                  <div class="news-img-main">
                    <div class="news-img"><img src="{{ images.{{ forloop.counter }}.image.url }}" alt="" data-popupalt-original-title="null" title="">
                      <div class="news-list">
                        <ul>
                          <li><i class="fa fa-clock-o" aria-hidden="true"></i> {{ project.date }}</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                  <div class="news-head">
                    <h3>{{ project.title }}</h3>
                  </div>
                </div>
            </div>
        {% endfor %}
    </div>

希望这是我想要做的。

我确定有人会告诉我我正在做错事,所以这是我的观点。py

def projects(request):
    projects = Project.objects.all()
    images = ProjectImage.objects.all()

    return render(request, 'projects.html', {'projects': projects,
                                             'images': images})

还有我的模型。py

class Project(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
    date = models.DateField()

    def __str__(self):
        return self.title


class ProjectImage(models.Model):
    project = models.ForeignKey(Project, related_name='images', on_delete='CASCADE')
    image = models.ImageField()

2 个答案:

答案 0 :(得分:1)

事实上,您不想执行任何操作。您在Project和ProjectImage之间有关系,您应该将项目传递到模板并在其中使用该关系。

{% for project in projects %}
    ...
    {% for image in project.images.all %} 
    <div class="news-img">
        <img src="{{ image.image.url }}" alt="" data-popupalt-original-title="null" title="">
    </div>
    {% endfor %}
    ...
{% endfor %}

答案 1 :(得分:0)

这是我最后使用的。

<div class="row">
        {% for project in projects.all %}
            <div class="col-md-4 col-sm-6">
                <div class="news-section-single">
                  <div class="news-img-main">
                    <div class="news-img"><img src="{{ project.images.first.image.url }}" alt="" data-popupalt-original-title="null" title="">
                      <div class="news-list">
                        <ul>
                          <li><i class="fa fa-clock-o" aria-hidden="true"></i> {{ project.date }}</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                  <div class="news-head">
                    <h3>{{ project.title }}</h3>
                  </div>
                </div>
            </div>
        {% endfor %}
    </div>