Home > Software design >  How can I display images from my Django DB?
How can I display images from my Django DB?

Time:11-18

Currently, although it may not be best practice, I have images stored in my django database and want to fetch them to display in a gallery page. However, I cannot get the image to display at all, which I think is because it does not arrive at the correct path.

 <img src ="{% static 'img/' object.image %}">

This code is to try and arrive at the correct directory for the uploaded image which is

\AFA\src\artForAll\static\img

Also object.image comes from this model

class GalleryPost(models.Model):
    title       = models.CharField(max_length=120)
    description = models.TextField(blank =True, null=True)
    artist      = models.CharField(max_length=120)
    featured    = models.BooleanField(default= False)
    image       = models.ImageField(null = True, blank = True, upload_to = "static/img/")

All of the other fields here work and I can see that the image is being uploaded to the correct place.

CodePudding user response:

As @Willem Van Onsem said in the comment, you can use <img src ="{{ object.image.url }}"> but, you need to check if image exists.

{% if object.image %}
    <img src ="{{ object.image.url }}">
{% else %}
    <img src ="<replace for default image url>">
{% endif %}
  • Related