如何使用 Django 显示我的图像?

How can I get my image to display using django?

我在使用 Django 时无法让我的图像显示在我的网页上。我所看到的只是显示的图像 'alt' 文本,以及旁边的破损图像图标。我能够按原计划成功上传图像。我正在为我的服务器使用安装了 Apache 的 Ubuntu AWS 实例。我还安装了 Pillow 来显示图像。

我也能够成功加载我的 CSS,所以我知道这可能不是我的静态目录或设置的问题。

这是我的 settings.py 文件:

import os
from pathlib import Path

# 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/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-)zp1^vv9%@3e*rz4yp0o964-^!8@ruff4$((b5vcv6*h@d-x'

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

ALLOWED_HOSTS = ['ec2-3-14-217-157.us-east-2.compute.amazonaws.com', '3.14.217.157']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'product.apps.ProductConfig',
]

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 = 'productapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        '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 = 'productapp.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'static')  # project level
STATIC_URL = 'static/'
# STATICFILES_DIRS = ['/var/www/productapp/static/']

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

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'index'

我的 urls.py 文件:

from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.http import HttpResponse
from django.urls import path, include


def home(request):
    return HttpResponse("Home page")


urlpatterns = [
    path('', TemplateView.as_view(template_name="index.html"), name="index"),
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('productapp/', include('product.urls', namespace='product'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

因为我使用的是 Apache,所以我尝试编辑 apache2.conf 文件以指向指定的媒体文件夹,如下所示:

Alias /media/ /var/www/prodictapp/media/
Alias /static /var/www/productapp/static/

<Directory /var/www/productapp/static>
Require all granted
</Directory>

<Directory /var/www/productapp/media>
Require all granted
</Directory>

WSGIScriptAlias / /var/www/productapp/productapp/wsgi.py
WSGIPythonPath /var/www/productapp

<Directory /var/www/productapp/productapp>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

模板:

{% extends 'product/base.html' %}

{% block title %}{{ product.name }} - Details{% endblock %}

{% block body %}
    <h3>Details for {{ product.name }}:</h3>
    <p>
        Name: {{ product.name }}<br>
        Price: ${{ product.price }}<br>
        Description: {{ product.description }}<br>
        Quantity: {{ product.quantity }}<br>
        {% if product.image %} {# If record has image, display it #}
            Product image: <br><img src="{{ product.image.url }}" alt="{{ product.name }}"><br>
        {% endif %}
    </p>
{% endblock %}

你可以试试这个

<img src="{% static product.image.url %}" />            # use this 
<img src="{{ MEDIA_URL }}{{ product.image.url}}" />      # or this