Home > Net >  Django show image list in table from ManyToMany field
Django show image list in table from ManyToMany field

Time:10-05

I have created a model to have details of job vacancy. The job model has the following fields:

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'

I want to use the hiring_team in a template to show image of each employee (circle avatar), and those images come from the employee model:

class Employee(models.Model):
    image = models.ImageField(blank=True, default='blank_profile_picture.jpg')

I've managed to display all images, but they are not in the same table cell, and they add additional table columns:

<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>

How can I "concatenate" them to display something like the screenshot below: Hiring team avatars

CodePudding user response:

This should mean the images should all be under one td block, so just put the td outside of the loop:

        <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>
  • Related