【问题标题】:Django show image list in table from ManyToMany fieldDjango在ManyToMany字段的表格中显示图像列表
【发布时间】:2021-10-04 15:49:15
【问题描述】:

我创建了一个模型来显示职位空缺的详细信息。作业模型具有以下字段:

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>

如何“连接”它们以显示如下屏幕截图:

【问题讨论】:

  • 听起来像是纯 CSS 问题?

标签: django django-models django-views django-templates


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 2013-07-16
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2016-06-01
    • 2012-11-15
    • 1970-01-01
    • 2017-07-11
    相关资源
    最近更新 更多