【问题标题】:Django: Cannot render images in templateDjango:无法在模板中渲染图像
【发布时间】:2021-03-04 13:11:33
【问题描述】:

我是编码新手。我无法在 book_detail.html 页面上呈现书籍封面(在 Django 管理中上传并存储在媒体/图像中)。

尝试添加以下内容,但随后出现此类型错误: MEDIA_ROOT = BASE_DIR('媒体') TypeError: 'PosixPath' 对象不可调用

我想我必须在 urls.py 中添加更多内容?毫无疑问,{{}} 中的 img src-tag 是错误的。试图理解和根本原因,但我猜有太多事情错了。 :) 我希望有人可以提供帮助。

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 %} 

更新1


按照 Answer1 中的建议,我已将 book_detail.html 更改为以下内容:

当 'python manage.py runserver' 我得到信息时:

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

我的 settings.py 也有这些用于引导模板的 DIR。这会干扰其他 Media_Root 条目吗?

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/'

【问题讨论】:

    标签: python django django-templates render


    【解决方案1】:

    更新您的 book_details.html

    {% block content %}
    
            <p>
                <img src="{{ object.cover.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 %} 
    

    只更新一行

    <img src="{{ photo.photo.url }}" alt="Image" width="300px">
    

    <img src="{{ object.cover.url }}" alt="Image" width="300px">
    

    【讨论】:

    • 谢谢。我已经更新了我的问题(请参阅上面帖子中的 Update1),因为我收到一条类型错误消息,因此看不到所做的更改。
    猜你喜欢
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 2014-01-25
    • 2014-11-22
    • 2022-07-22
    • 2016-02-26
    • 1970-01-01
    • 2018-05-20
    相关资源
    最近更新 更多