【问题标题】:Images in Django aren't loading even though they're stored locally即使图像存储在本地,Django 中的图像也不会加载
【发布时间】:2020-08-02 01:10:08
【问题描述】:

使用我目前拥有的代码,我的图像过去可以加载,但现在无法加载,我不知道为什么。在我的 Artist 模型中,我包含了一个 ImageField。这让我可以上传图像并将其存储在我的媒体目录中名为“艺术家”的目录中。

class Artist(models.Model):
name = models.CharField(max_length=40)
genre = models.CharField(max_length=20)
location = models.CharField(max_length=20)
bio = models.TextField()
photo = models.ImageField(upload_to='artists', null=True, blank=True)

def __str__(self):
    return self.name

如下所示,我的图片“fontaines.png”已上传并存储在 /media/artists/ 中。

├── db.sqlite3
├── manage.py
├── media
│   ├── artists
│   │   └── fontaines.png
├── mysite
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-38.pyc
│   │   ├── settings.cpython-38.pyc
│   │   ├── urls.cpython-38.pyc
│   │   └── wsgi.cpython-38.pyc
│   ├── asgi.py
│   ├── settings.py
│   ├── static
│   │   └── main.css
│   ├── templates
│   │   └── base.html
│   ├── urls.py
│   └── wsgi.py
└── pages
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-38.pyc
    │   ├── admin.cpython-38.pyc
    │   ├── apps.cpython-38.pyc
    │   ├── forms.cpython-38.pyc
    │   ├── models.cpython-38.pyc
    │   ├── urls.cpython-38.pyc
    │   └── views.cpython-38.pyc
    ├── admin.py
    ├── apps.py
    ├── forms.py
    ├── migrations
    │   ├── 0001_initial.py
    │   ├── 0002_artist.py
    │   ├── __init__.py
    │   └── __pycache__
    │       ├── 0001_initial.cpython-38.pyc
    │       ├── 0002_artist.cpython-38.pyc
    │       └── __init__.cpython-38.pyc
    ├── models.py
    ├── templates
    │   └── pages
    │       ├── artist.html
    │       ├── home.html
    │       ├── login.html
    │       ├── page.html
    │       ├── profile.html
    │       ├── signup.html
    │       ├── upload.html
    │       └── venue.html
    ├── tests.py
    ├── urls.py
    └── views.py

到目前为止,一切看起来都很好,但是当我在本地运行服务器时,它会在我的终端上显示图像的页面上这样说:

Not Found: /media/artists/fontaines.png
[19/Apr/2020 15:32:01] "GET /media/artists/fontaines.png HTTP/1.1" 404 1759

我试图弄清楚为什么图像无法加载,但我就是无法破解它。可以的话请帮忙,谢谢。

编辑: 下面是我的 urls.py 文件

from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

from . import views
from django.urls import path, include

urlpatterns = [
    url(r'^signup$', views.signup, name='signup'),
    url(r'^login$', views.user_login, name='login'),
    url(r'^logout$', views.logout_request, name='logout'),
    url(r'^profile$', views.profile, name='profile'),
    url(r'^artist$', views.artists, name='artist'),
    url(r'^venue$', views.venues, name='venues'),
    url(r'([^/]*)', views.home, name='home'),
]

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

下面是我的 settings.py 文件

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$b4y%d7(x*rhpqo_#t9k)c5ppvrgwmco%q-v46mfdo!31ksly*'

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

ALLOWED_HOSTS = ['127.0.0.1']


# Application definition

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

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'mysite/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 = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'USER': 'affix',
        'PASSWORD': 'robbrennan',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.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/3.0/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.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'mysite/static'),
]

LOGIN_REDIRECT_URL = '/'

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

MEDIA_URL = '/media/'

下面是我的 artist.html 文件:

{% extends 'pages/page.html' %}
{% load static %}
{% block content %}
    <h1>AFFIX</h1>
    <title>AFFIX - Artists</title>
    <h2><i>// Browse Artists on AFFIX //</i></h2>
    <br>
    {% for artist in artists %}
    <div id="container">
        {% if artist.photo %}
            <img src="{{ artist.photo.url }}" alt="{{ artist.name }}" style="width:360px; float:right; margin-left: 40px; margin-bottom: 40px;">
        {% else %}
            <p1>No Photo Uploaded</p1>
        {% endif %}
        <h3>{{ artist.name }}</h3>
        <p class="a"><i>Submitted By {{ artist.author }} on {{ artist.date_posted|date:"F d, Y" }}</i></p>
        <p class="a"><b>Genre:</b> {{ artist.genre }}<br><b>Location:</b> {{ artist.location }}</p>
        <details>
            <summary>Expand</summary>
            <p class="a">{{ artist.bio }}</p>
        </details>
    </div>
    <br>
    {% endfor %}
<br>
{% endblock content %}

【问题讨论】:

  • 您的根 urls.py 文件中的媒体根配置完成了吗?
  • 是的,我相信我有。我已经编辑了上面的问题,并包含了我当前的 urls.py 和 settings.py 文件。
  • 在调用图片的地方添加模板代码
  • 我现在已经完成了,在上面添加了我的艺术家.html 代码
  • 有什么想法吗?

标签: python html django image imagefield


【解决方案1】:

您是否在 HTML 模板中加载了静态文件?

{% load static %}

【讨论】:

  • 我做了,但是他们仍然没有加载并且仍然在我的终端中找不到:/media/artists/fontaines.png。
猜你喜欢
  • 2014-02-19
  • 1970-01-01
  • 2020-08-15
  • 2013-03-27
  • 2015-11-08
  • 1970-01-01
  • 2016-01-24
  • 2011-08-04
  • 2021-11-20
相关资源
最近更新 更多