首页 > 解决方案 > 在 django 管理站点上添加多个图像并显示在详细信息页面上

问题描述

我正在处理一个投资组合项目,我想在 Django 管理站点上添加多个图像,然后在主页/列表页面上显示项目的 header_image 和标题之一(如引导程序中的卡片类功能)和其他图像详情页。可能吗?

Models.py

class MultiImage(models.Model): 
    header_image = models.ImageField(upload_to='media/')
    title = models.CharField(max_length=100)
    other_images = models.ImageField(upload_to='media/') # want this to be multiple image field
    description = models.TextField()
    link = models.URLField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    publish = models.BooleanField(default=True)

    class Meta:
        ordering = ('created', 'updated')

    def __str__(self):
        return self.title

索引.html

{% for project in projects %}
 <div class="col-lg-4 col-md-6 portfolio-item filter-app">
  <div class="portfolio-wrap">
   <img src="{{ project.image.url }}" class="img-fluid" alt="">
   <div class="portfolio-links">
    <a href="{{ project.image.url }}" data-gall="portfolioGallery" class="venobox" title="{{ project.title }}"><i class="bx bx-plus"></i></a>
    <a href="{% url 'detail' project.id %}" title="More Details"><i class="bx bx-link"></i></a>
   </div>
  </div>
 </div>
{% endfor %}

详细信息.html

<div class="container">
 <div class="portfolio-details-container">

  <div class="owl-carousel portfolio-details-carousel">
   <img src="{% static 'img/portfolio-details-1.jpg' %}" class="img-fluid" alt=""> 
   <!-- all the images goes here -->
  </div>

  <div class="portfolio-info">
   <h3>Project Information</h3>
   <ul>
    <li><strong>Project </strong>: {{ project.title }}</li>
    <li><strong>Project Link to GitHub:</strong>: <a href="{{ project.link }}">{{ project.title }}</a </li>
   </ul>
  </div>

 </div>
</div>

列表/索引页 img

详细页面 img1 详细页面 img2

标签: djangodjango-templatesdjango-admin

解决方案


如果您想针对单个MultiImage对象存储多个图像,最好的方法是创建一个单独的图像模型(您将在其中存储所有图像),然后使用外键将它们指向MultiImage实例。它看起来像这样:

class Image(models.Model):
    # add in anything else you want here
    image = models.ImageField((upload_to='media/')
    multiImage = models.ForeignKey(Reporter, on_delete=models.CASCADE, related_name='other_images')

这意味着,您创建的每个图像都“指向”一个MultiImage实例。该related_name属性是您获取所需的所有图像的方式。例如:

multi_image_instance = MultiImage.objects.get(id=...)
images = multi_image_instance.other_images # this will return a QuerySet

在详细视图中,您可以执行以下操作:

{% for image in images %}
    <img src={image.image.url} />
{% endfor %}

推荐阅读