如何在Django模板中循环显示外键中类别的所有图像?

时间:2018-08-16 23:06:14

标签: python django django-models django-views django-queryset

我正在自己做一个django练习,这次是关于CV(简历)网站的,在Portfolio部分中,它显示了项目的(标题,客户和描述),下面的地方,一个画廊(使用bootstrap carrousel)来自该项目的所有图像。我已经在views.py中尝试了一些过滤器,但无法获取每个图像的分离图像。还希望在模板中进行过滤,但两者都不是。

所以输出将是这样的:

组合部分

名称:实践项目1 客户: Peter Parker

(此项目中所有与图像有关的图像)


名称: Practice Project 2 客户:巴拉克·奥巴马

(此项目中所有与图像有关的图像)


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

代码:

models.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

views.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)

index.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>

1 个答案:

答案 0 :(得分:0)

使用django中包含的_set.all解决,循环浏览并在引导程序转盘中显示每个图像。发现于:

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

python - Django display uploaded multiple images with foreign key

结果是:

models.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”自变量

views.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)

index.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'}}以及将引导程序转盘和灯箱插件投入运行的细节