Home > Blockchain >  image not showing in the templates in django
image not showing in the templates in django

Time:12-20

this my templates when i add song from my database everything is working fine but image not showing in the templates how can i solve that this is my templates. {% for audio in songs %}

 <div >

    <div >
      <div>
        <p>{{audio.book_title}}</p>

        <p>{{audio.artist}}</p>

        <p>{{audio.author}}</p>
      </div>
        <img src="{{object.image_url}}" alt="">
    </div>
    <audio controls>

    <source src="{{audio.file.url}}" type="audio/mp3">
    </audio>
 </div>
 {% endfor %}

this is my models.py from django.db import models

Create your models here.

class Audio(models.Model):

book_title = models.CharField(max_length=100, null=False, blank=False)



file = models.FileField(upload_to='file')



author = models.CharField(max_length=100, null=False, blank=False)



artist = models.CharField(max_length=100, null=False, blank=False)



image = models.ImageField(upload_to=file, null=True, blank=False)




def __str__(self):


    return self.book_title



    def image_url():



        if self.image and hasattr(self.image, 'url'):




            return self.image.url

this is my views.py

from django.shortcuts import render

from .models import Audio

Create your views here.

def index(request):

context = {'songs': Audio.objects.all()}



return render(request, 'index.html', context)

CodePudding user response:

You can make you of python Property inside of your django models like below.

class Audio(models.Model):
    book_title = models.CharField(max_length=100, null=False, blank=False)
    file = models.FileField(upload_to="file")
    author = models.CharField(max_length=100, null=False, blank=False)
    artist = models.CharField(max_length=100, null=False, blank=False)
    image = models.ImageField(upload_to=file, null=True, blank=False)

    def __str__(self):
        return self.book_title

    @property
    def image_url(self):
        """
        Returns a image url if the audio has an image.
        """
        return self.image.url if self.image else None

CodePudding user response:

I think you have a mistake in <img src="{{object.image_url}}" alt="">, which should be <img src="{{audio.image.url}}" alt="">

  • Related