Displaying uploaded images in Django

Say you have a model that handles images like this:

import uuid
from django.db import models

class AwesomeImages(models.Model):
    """ All the awesome images from the interwebs """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200)
    image = models.ImageField(upload_to='awesome/', blank=True, null=True)

    def __str__(self):
        return self.name

To get it showing in your template you need these settings (here all files go into the media directory):

...

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

...

THEN in your main urls.py file you need this line so that the Django local server will serve images:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    ....
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The docs aren’t hugely clear on the line needs in the urls.py file.

To show the file in your template you call the awesomemodel.image.url attribute.

Tags:

Leave a Reply