0

使用我目前拥有的代码,我的图像过去可以加载,但现在它们没有,我不知道为什么。在我的 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/'

下面是我的艺术家.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 %}
4

1 回答 1

0

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

{% load static %}
于 2020-04-19T15:59:28.163 回答