无法显示来自 django 模型的图像

Can't display images from models of django

这个问题我遇到过很多次都找不到解决办法,求助

这是我的设置文件。我已经配置了媒体根

from pathlib import Path
import os
import django_heroku
import django
# 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/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc@13'

# 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',
    'home',
]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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 = 'testimage.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',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,"static")]
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')


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

django_heroku.settings(locals())

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

这是一个简单的模型,仅用于添加和显示图像

from django.db import models

# Create your models here.
class Images(models.Model):
    photo = models.ImageField(blank=True, null=True, default=None)
    title = models.CharField(max_length=250)
    def __str__(self):
        return self.title

这是我的 views.py 和模板

from django.shortcuts import render
from home.models import Images
# Create your views here.
def index(request):
    images = Images.objects.all()
    context = {
        'images':images
    }
    return render(request,'home.html',context)

home.html

{%for i in images %}
<img src="{{i.photo.url}}" alt="">
{%endfor%}

每次我尝试加载该页面时,总是会出现此错误:

[15/Feb/2021 11:57:12] "GET /media/20210129_205930.jpg HTTP/1.1" 404 2130
[15/Feb/2021 11:57:12] "GET /media/20201227_111422.jpg HTTP/1.1" 404 2130

我知道它告诉我媒体路径有问题,但我检查了所有但找不到任何错误点。请看一下

您的 url.py 文件中似乎没有添加媒体 URL,因此您可以这样做

# make your imports
from django.conf import settings 
from django.conf.urls.static import static

urlpatterns = [
      ....
]

# for Debugging
if settings.DEBUG:
    urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我希望你完成上面提到的所有 url.py 代码 所以图像是一个文件,所以你必须像这样请求文件

def index(request.FILES, request.POST):
    images = Images.objects.all()
    context = {
              'images':images
                }
    return render(request,'home.html',context)

在你的 html 文件表单标签中使用 enctype

<form action="{% url 'name' %}" method'POST' enctype="multipart/form-data">

并从图像中删除默认设置 class 如果您希望图像可以为空白=True 不需要默认,我可以在你的模型中看到你没有定义路径,你的图像必须像这样存储

profile_pic = models.ImageField(upload_to='profile_pics',default='default.png',)

并在您的主要 urls.py 添加

+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

希望这对您有所帮助,如果您有任何错误请告诉我