python - Django 静态文件未加载 ImageField URL
问题描述
这是一个作业,我们需要将图像存储在静态目录中并在模板上显示它们。图片通过项目模型 ImageField 存储并上传到 static/images 目录。
这是模板代码:
{% load static %}
<p><a href='..'>Home</a></p>
{% block content %}
<table>
<tr>
<th>Item Name</th>
<th>Manufacturer</th>
<th>Cost</th>
<th>Weight</th>
<th>Image</th>
</tr>
{% for i in name %}
{% if i.name == params %}
<tr>
<td>{{i.name}}</td>
<td>{{i.manufacturer}}</td>
<td>{{i.cost}}</td>
<td>{{i.weight}}</td>
<td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td>
</tr>
{% endif %}
{% endfor %}
</table>
{% endblock %}
我有以下型号代码:
from django.db import models
class item(models.Model):
name = models.CharField(max_length=40)
manufacturer = models.CharField(max_length=255)
cost = models.DecimalField(max_digits=10, decimal_places=2)
weight = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='static/images/')
以下是当前设置
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 = 'Nice try'
# 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',
'mysite',
]
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': [],
'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'),
}
}
# 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/'
ALLOWED_HOSTS = ['*']
X_FRAME_OPTIONS = '*'
目前,模型类中的所有内容都可以正常显示,但是在为 img src 尝试了一百万个不同的标签后,图像将无法加载。我们应该使用静态,所以请不要建议使用媒体目录来存储图像。
感谢您的帮助。
解决方案
假设在您的 views.py 中,您有:
name = item.objects.all()
然后将变量name
传递给您的模板,
试着用这个代替
<td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td>
有了这个
<td><img src="{{ i.image.url }}" alt="{{i.image.url}}"></img></td>
但是,我建议您使用name
更具代表性的名称来调用变量,例如objects_list
,那么您将拥有
{% for i in objects_list %}
{% if i.name == params %}
<tr>
<td>{{i.name}}</td>
<td>{{i.manufacturer}}</td>
<td>{{i.cost}}</td>
<td>{{i.weight}}</td>
<td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td>
</tr>
{% endif %}
{% endfor %}
这更清楚。
推荐阅读
- docker - Docker 似乎无法找到本地存储的图像
- amazon-s3 - 如何解决 SPA 上的“x-cache:来自云端的错误”
- graphql - GraphQL 类型查询:出现错误“预期名称,找到字符串‘类型’”
- angular - Angular 7 - Highcharts 标题不变
- c++ - 在命名空间中定义变量
- c# - 连字符是否在 LDAP DN 中编码?
- c# - 分组和替换
- python - CUDA 文件丢失,我该如何获取?
- azure-devops - 如何通过 ARM 模板在 Azure CDN 的 CustomDomain 中启用 HTTPS
- r - 审查数据以进行生存分析