Django: Cannot render images in template

I am new to coding. I am not able to render the book-covers (uploaded in Django admin and stored in media/images) on my book_detail.html-page.

Tried to add the below but then get this typeerror: MEDIA_ROOT = BASE_DIR('media') TypeError: 'PosixPath' object is not callable

I think I have to add more to urls.py? Definitely, the img src-tag in {{ }} is wrong. Tried to comprehend and root cause but there are too many things wrong, I guess. :) I hope, someone can help.

urls.py

    path('', BookListView.as_view(), name='book_list'),
    path('<int:pk>/', BookDetailView.as_view(), name='book_detail'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #added 

settings.py

MEDIA_ROOT = BASE_DIR('media')
MEDIA_URL = '/media/'

STATIC_ROOT = BASE_DIR('staticfiles')
STATIC_URL = '/static/' 

models.py

class Book(models.Model):
cover = models.ImageField(upload_to='images/', null=True)     

title = models.CharField(max_length=200, help_text='Capitalize first letters. No 
subheadlines.') 
    
author = models.ForeignKey(to=Author, on_delete=models.SET_NULL, null=True, 
related_name='books')
    

book_detail.html

{% block content %}

        <p>
            <img src="{{ photo.photo.url }}" alt="Image" width="300px">
            <!-- <img src="{{ cover_image.url }}" alt="Image" width="250" height="250"> -->
        </p>

        
        <h1>{{ object.title }} {{ block.super }}</h1> 
        <p class="lead"><em>by {{ object.author }}</em></p>
                
        # more code here

{% endblock %} 

UPDATE1


As recommended in Answer1 I have changed book_detail.html to the following:

When 'python manage.py runserver' I get the info:

MEDIA_ROOT = BASE_DIR('media') TypeError: 'PosixPath' object is not callable

My settings.py has also these DIRs for bootstrap-templates. Does that interfere with the the other Media_Root entries?

from pathlib import Path
import os # Imported for DIRS in Templates below

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# Secret Key

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books', # App
    'multiselectfield', # For multiselect of genres
    'bootstrap4', # Bootstrap4
    'ckeditor', # WYSIWYG Editor
    'ckeditor_uploader', # WYSIWYG Editor
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'booklist.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'),],   # Bootstrap4
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'booklist.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Static files (CSS, JavaScript, Images)
MEDIA_ROOT = BASE_DIR('media')
MEDIA_URL = '/media/'

STATIC_ROOT = BASE_DIR('staticfiles')
STATIC_URL = '/static/'

BOOTSTRAP4 = { 'include_jquery': True } # Bootstrap4


# WYSIWYG Editor
CKEDITOR_UPLOAD_PATH = 'uploads/'
MEDIA_URL = '/media/' 
MEDIA_ROOT = 'media/'



Read more here: https://stackoverflow.com/questions/64940997/django-cannot-render-images-in-template

Content Attribution

This content was originally published by Seb at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: