django - Django在ManyToMany字段的表格中显示图像列表
问题描述
我创建了一个模型来显示职位空缺的详细信息。作业模型具有以下字段:
class Job(models.Model):
job_position = models.ForeignKey(Position, on_delete=models.PROTECT, related_name='job_position')
applicants_to_hire = models.IntegerField(null=True, blank=True,
validators=[MinValueValidator(1), MaxValueValidator(15)], default=1)
hiring_team = models.ManyToManyField(Employee, related_name='hiring_team')
class JobListView(LoginRequiredMixin, ListView):
model = Job
template_name = 'recruitment/job_list.html'
context_object_name = 'job_list'
我想在模板中使用hiring_team来显示每个员工的图像(圆形头像),这些图像来自员工模型:
class Employee(models.Model):
image = models.ImageField(blank=True, default='blank_profile_picture.jpg')
我已经设法显示所有图像,但它们不在同一个表格单元格中,并且它们添加了额外的表格列:
<tbody>
{% for job in job_list %}
<tr>
<td><span class="employee-table-name"><a href="{% url 'recruitment:job_detail' pk=job.pk %}">{{ job.job_position }}</a></span></td>
<td>{{ job.applicants_to_hire }}</td>
{% for team in job.hiring_team.all %}
{% if team.image %}
<td><img src="{{ team.image.url }}" class="rounded-circle img-fluid-80" alt="{{ team }}"></td>
{% endif %}
{% endfor %}
<td>{{ job.job_priority }}</td>
<td>{{ job.job_status }}</td>
<td>{{ job.created|date:"M d, Y" }}</td>
</tr>
{% endfor %}
</tbody>
解决方案
这应该意味着图像都应该在一个td
块下,所以只需将td
循环放在外面:
<td>
{% for team in job.hiring_team.all %}
{% if team.image %}
<img src="{{ team.image.url }}" class="rounded-circle img-fluid-80" alt="{{ team }}">
{% endif %}
{% endfor %}
<td>
推荐阅读
- java - 将数据传递给 Intent 并填充文本视图
- php - 嵌套foreach,如何更高效
- c# - 为什么我必须在循环中输入两次度数?
- ruby - 来自 Model.search 和 SearchKick.search 的不同结果,带有 named_index
- python - Python Regex[Forking] - 根据术语捕获组,但如果遇到集合中的另一个术语则跳过
- python - 查询实体的正则表达式
- spacy - SpaCy:从字符索引中获取令牌
- linux - 如何从 perf 报告中获取 PEBS 数据线性地址和延迟值?
- spring-boot - spring cloud config服务器-客户端刷新策略
- r - 如何通过向函数添加输出来防止重写闪亮的块?