django - 在 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>
解决方案
如果您想针对单个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 %}
推荐阅读
- python - Python 中的单独 print() 结果
- reactjs - 如何防止 useEffect 中的函数被多次触发?
- python - matplotlib 动画,用于在单个图形中同步移动多个形状
- html - CSS初学者,需要帮助定位重叠的DIV
- ruby-on-rails - 删除枚举的默认值
- javascript - 渲染前获取数据 [React Native]
- php - 在博客存档页面上显示 ACF
- android-studio - Android Studio可以用aosp模拟器调试吗
- excel - Excel:按范围内的单元格计算多个字符
- react-native - OnPress 不起作用 React Native - Android