Subhajit Podder
Subhajit Podder

Reputation: 65

How to display image in a HTML page the Django Framework?

I have a webpage which will show the logo of an music album. For that I've added a database field named album_ logo and add the path name of the images folder "C:\Python Projects\Test_App\website\music\static\music\Image" in database. But in the HTML page album_logo is not rendering.

Here is the attached code snippet.

<body>
{% load static %}
<img src = "{{album.album_logo}}">

<h1>{{album.album_title}}</h1>
<h3>{{album.artist}} - {{album.genre}}</h3>
</body>

Create your models here.

class Album(models.Model):
    album_title = models.CharField(max_length=250)
    artist = models.CharField(max_length=250)
    genre = models.CharField(max_length=100)
    album_logo = models.CharField(max_length=500)

    def __str__(self):
        return self.album_title + '-' + self.artist

Example: For the first album I've added the image path in database as - "C:\Python Projects\Test_App\website\music\static\music\Image\The_Division_Bell.jpg"

Upvotes: 2

Views: 408

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

album_logo should be ImageField since it is a image. Also you need to do pip install pillow to upload the images.

In your models

.......................
album_logo = models.ImageField(upload_to='alubm_logo')

and in your project's urls.py you need to provide the static url like this (Note:this is only for development)

project/urls.py

urlpatterns=[.......
 ................
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Upvotes: 2

Related Questions