首页 > 解决方案 > 如何在django模板中循环显示外键中的所有类别图像?

问题描述

我正在自己做一个 django 练习,这次是关于 CV(简历)网站,在 Portfolio 部分它显示了项目的(标题、客户和描述),在下面,一个画廊(使用引导轮播)所有图像从那个项目。我在 views.py 中尝试了一些过滤器,但我无法为每个过滤器获取分离的图像。也在寻找模板中的过滤,但也没有。

所以输出会是这样的:

投资组合部分

名称:实践项目 1 客户:彼得·帕克

(本项目轮播中的所有图像)


名称:实践项目2 客户:巴拉克奥巴马

(本项目轮播中的所有图像)


我需要显示与其项目相关的所有图像

代码:

模型.py:

from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField

# Create your models here.

class Project(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    name = models.CharField(verbose_name='Nombre del proyecto', max_length=200)
    client = models.CharField(verbose_name='Nombre del cliente', max_length=200)
    description = RichTextField(verbose_name='Descripción')
    start = models.DateField(verbose_name='Fecha de Inicio', null=True, blank=True)
    ending = models.DateField(verbose_name='Fecha de Finalización', null=True, blank=True)
    order = models.SmallIntegerField(verbose_name="Orden", default=0)
    created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True)
    updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True)

    class Meta:
        verbose_name = 'Proyecto'
        verbose_name_plural = 'Proyectos'
        ordering = ['-start', 'order']

    def __str__(self):
        return self.name

class Album(models.Model):
    album = models.ForeignKey(Project, related_name='images', on_delete = models.CASCADE)
    title = models.CharField(verbose_name='Título de la imagen', max_length=200, null=True, blank=True)
    image = models.ImageField(verbose_name='Imagen', upload_to='portfolio')
    created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True)
    updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True)

    class Meta:
        verbose_name = 'Imagen en el album'
        verbose_name_plural = 'Imágenes en el album'
        ordering = ['created']

        def __str__(self):
            return self.title

视图.py:

from django.shortcuts import render
from django.views.generic.list import ListView

from certifications.models import Certification
from education.models import Education
from experience.models import Experience
from registration.models import Profile
from portfolio.models import Project, Album

# VISTAS DE LA APP CORE

class HomePageView(ListView):
    template_name = "core/index.html"

    def get(self, request, *args, **kwargs):

        certifications_list = Certification.objects.all()
        education_list = Education.objects.all()
        experience_list = Experience.objects.all()

        profile_list = Profile.objects.all()
        profile = Profile.objects.get(id=1)

        project_list = Project.objects.all()

        album_list = Album.objects.all()

        context = {
            'title':'mytitle',
            'certifications_list':certifications_list,
            'education_list':education_list,
            'experience_list':experience_list,
            'profile_list':profile_list,
            'profile':profile,
            'project_list':project_list,
            'album_list':album_list,

            }
        return render(request, self.template_name, context)

索引.html:

<section class="resume-section p-3 p-lg-5 d-flex flex-column" id="portfolio">
    <div class="my-auto">
        <h2 class="mb-5">Portafolio</h2>
        {% for project in project_list %}
          <div class="resume-item d-flex flex-column flex-md-row mb-5">
            <div class="resume-content mr-auto">

                <h3 class="mb-0">{{project.name}}</h3>
                <div class="subheading mb-3">{{project.client}}</div>

                <p>
                    <button class="btn btn-secondary btn-sm mt-0" type="button" data-toggle="collapse" data-target="#collapseExample{{project.id}}" aria-expanded="false" aria-controls="collapseExample">
                      Ver más
                  </button>
                  </p>
                  <div class="collapse" id="collapseExample{{project.id}}">
                      <small>
                          {{project.description|safe}}
                      </small>   
                  </div>

                  <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval='false'>

                      <ol class="carousel-indicators">
                        <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                        {% for album in album_list %}
                        <li data-target="#myCarouse{{forloop.counter}}" data-slide-to="{{forloop.counter}}"></li>
                        {% endfor %}
                      </ol>

                      <div class="carousel-inner">

                      {% for album in album_list %}

                        {% if forloop.first %}
                          <div class="carousel-item active">
                              <a class="" href="{{album.image.url}}" data-lightbox="count-{{project.name}}" data-title="{{album.title}}">
                                <img class="img-fluid rounded custom-shadow mb-2" src="{{album.image.url}}" alt="">
                              </a>
                          </div>

                        {% else %}

                        <div class="carousel-item">
                            <a class="" href="{{album.image.url}}" data-lightbox="count-{{project.name}}" data-title="{{album.title}}">
                              <img class="img-fluid rounded custom-shadow mb-2" src="{{album.image.url}}" alt="">
                            </a>
                        </div>
                        {% endif %}
                      {% endfor %}
                      </div>

                      <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev">
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="sr-only">Previous</span>
                      </a>
                      <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next">
                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        <span class="sr-only">Next</span>
                      </a>

                  </div>

              </div>

              <div class="resume-date text-md-right">
                  {% if project.ending %}
                    <ul class="fa-ul mb-0">
                      <li>
                        <i class="fa-li fa fa-calendar"></i>
                        <p class="mt-0 mb-0 text-primary">Del {{project.start}} al {{project.ending}}</p>
                      </li>
                    </ul>
                  {% endif %}
              </div>
          </div>
        {% if not forloop.last %}
        <hr> 
        {% endif %}
        {% endfor %}

    </div>

</section>

标签: pythondjangodjango-modelsdjango-viewsdjango-queryset

解决方案


使用_set.all包含在 django 中的解决方案,循环遍历它并在引导轮播中显示每个图像。在发现:

https://www.youtube.com/watch?v=6lafzyjiqgQ

python - Django 显示使用外键上传多个图像

结果是:

模型.py:

from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField

# Create your models here.

class Project(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    name = models.CharField(verbose_name='Nombre del proyecto', max_length=200)
    client = models.CharField(verbose_name='Nombre del cliente', max_length=200)
    description = RichTextField(verbose_name='Descripción')
    start = models.DateField(verbose_name='Fecha de Inicio', null=True, blank=True)
    ending = models.DateField(verbose_name='Fecha de Finalización', null=True, blank=True)
    order = models.SmallIntegerField(verbose_name="Orden", default=0)
    created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True)
    updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True)

    class Meta:
        verbose_name = 'Proyecto'
        verbose_name_plural = 'Proyectos'
        ordering = ['-start', 'order']

    def __str__(self):
        return self.name

class Album(models.Model):
    project = models.ForeignKey(Project, on_delete = models.CASCADE)
    title = models.CharField(verbose_name='Título de la imagen', max_length=200, null=True, blank=True)
    image = models.ImageField(verbose_name='Imagen', upload_to='portfolio')
    created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True)
    updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True)

    class Meta:
        verbose_name = 'Imagen en el album'
        verbose_name_plural = 'Imágenes en el album'
        ordering = ['created']

        def __str__(self):
            return self.title

1) FK 名称更改为“项目”

2) 删除了“related_name”参数

视图.py:

from django.shortcuts import render
from django.views.generic.list import ListView

from certifications.models import Certification
from education.models import Education
from experience.models import Experience
from registration.models import Profile
from portfolio.models import Project, Album

# VISTAS DE LA APP CORE

class HomePageView(ListView):
    template_name = "core/bloques.html"

    def get(self, request, *args, **kwargs):

        certifications_list = Certification.objects.all()
        education_list = Education.objects.all()
        experience_list = Experience.objects.all()

        profile_list = Profile.objects.all()
        profile = Profile.objects.get(id=1)

        project_list = Project.objects.all()

        album_list = Album.objects.all()

        context = {
            'title':'nilsoviani',
            'certifications_list':certifications_list,
            'education_list':education_list,
            'experience_list':experience_list,
            'profile_list':profile_list,
            'profile':profile,
            'project_list':project_list,
            'album_list':album_list,

            }
        return render(request, self.template_name, context)

索引.html:

<section class="resume-section p-3 p-lg-5 d-flex flex-column" id="portfolio">
    <div class="my-auto">
        <h2 class="mb-5">Portafolio</h2>
        {% for project in project_list %}
          <div class="resume-item d-flex flex-column flex-md-row mb-5">
            <div class="resume-content mr-auto">

                <h3 class="mb-0">{{project.name}}</h3>
                <div class="subheading mb-3">{{project.client}}</div>

                <p>
                    <button class="btn btn-secondary btn-sm mt-0" type="button" data-toggle="collapse" data-target="#collapseExample{{project.id}}" aria-expanded="false" aria-controls="collapseExample">
                      Ver más
                  </button>
                  </p>
                  <div class="collapse" id="collapseExample{{project.id}}">
                      <small>
                          {{project.description|safe}}
                      </small>   
                  </div>

                  <div id="myCarousel-{{ project.name|cut:" " }}" class="carousel slide" data-ride="carousel" data-interval='false'>

                      <ol class="carousel-indicators">

                        {% for album in project.album_set.all %}
                        <li data-target="#myCarousel-{{ project.name|cut:" " }}" data-slide-to="{{forloop.counter|add:'-1'}}" class="{% if forloop.first %} active {% endif %}"></li>

                        {% endfor %}
                      </ol>

                      <div class="carousel-inner">

                          {% for album in project.album_set.all %}

                        {% if forloop.first %}
                          <div class="carousel-item active">
                              <a class="" href="{{album.image.url}}" data-lightbox="count-{{project.name}}" data-title="{{album.title}}">
                                <img class="img-fluid rounded custom-shadow mb-2" src="{{album.image.url}}" alt="">
                              </a>
                          </div>

                        {% else %}

                        <div class="carousel-item">
                            <a class="" href="{{album.image.url}}" data-lightbox="count-{{project.name}}" data-title="{{album.title}}">
                              <img class="img-fluid rounded custom-shadow mb-2" src="{{album.image.url}}" alt="">
                            </a>
                        </div>
                        {% endif %}
                      {% endfor %}
                      </div>

                      <a class="carousel-control-prev" href="#myCarousel-{{ project.name|cut:" " }}" role="button" data-slide="prev">
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="sr-only">Previous</span>
                      </a>
                      <a class="carousel-control-next" href="#myCarousel-{{ project.name|cut:" " }}" role="button" data-slide="next">
                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        <span class="sr-only">Next</span>
                      </a>

                  </div>

              </div>

              <div class="resume-date text-md-right">
                  {% if project.ending %}
                    <ul class="fa-ul mb-0">
                      <li>
                        <i class="fa-li fa fa-calendar"></i>
                        <p class="mt-0 mb-0 text-primary">Del {{project.start}} al {{project.ending}}</p>
                      </li>
                    </ul>
                  {% endif %}
              </div>
          </div>
        {% if not forloop.last %}
        <hr> 
        {% endif %}
        {% endfor %}

      </div>

  </section>

1) {% for album in project.album_set.all %} 用于循环专辑模型,对于与项目模型相关的每个图像

2) myCarousel-{{ project.name|cut:" " }} {{forloop.counter|add:'-1'}}和细节投入使用 bootstrap carrousel 和 lightbox 插件


推荐阅读