0

Django doesn't show images from ImageField in a template.

models.py

class Employee(models.Model):
    emp_name = models.CharField(max_length=200)
    emp_email = models.EmailField()
    emp_contact = models.CharField(max_length=20)
    emp_role = models.CharField(max_length=200)
    emp_salary = models.IntegerField()
    venue_image = models.ImageField(null=True, blank=True, upload_to="images/")
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

    def __str__(self):
        return self.emp_name

template:

<tbody>

    {% for emp in employees %}
        <tr>
            <th scope="row">{{ emp.emp_name }}</th>
            <td>{{ emp.emp_email }}</td>
            <td>{{ emp.emp_contact }}</td>
            <td>{{ emp.emp_role }}</td>
            <td>{{ emp.emp_salary}}</td>
            <td>
                <a style="margin-right: 30px;" href="{% url 'edit-employee' emp.id %}">EDITAR</a>
                <a href="{% url 'delete-employee' emp.id %}">ELIMINAR</a>
            </td>
            <td>
             {%if venue.venue_image%}
             {{venue.venue_image.url}}
             {%endif%}
            </td>
        </tr>
    {% endfor %}
</tbody>

views.py enter image description here

I'm expecting the image here: enter image description here

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39

1 Answers1

1

The issue is with your if condition in your template. You are getting your employees data with for loop and using variable emp not venue. Use this if condition and your image url will be displayed

{% if emp.venue_image %}
    {{emp.venue_image.url}}
{% endif %}

If you want to display the image you need to use image tag like this

{% if emp.venue_image %}
    <img src="{{emp.venue_image.url}}">
{% endif %}
Usama Saeed
  • 331
  • 4
  • 16