首页 > 解决方案 > 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>

如何“连接”它们以显示如下屏幕截图: 招聘团队头像

标签: djangodjango-modelsdjango-viewsdjango-templates

解决方案


这应该意味着图像都应该在一个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>

推荐阅读