如何从ImageField中加载一个模型的所有实例的图像



我有一个叫todo的应用,一个带ImageField的好模型。在我的模板中,我想迭代好模型的所有实例,并显示所有实例的图像由管理员在管理面板中上传,但当我尝试运行下面的代码时,我得到:未找到:/todo/static/goods_images/image_2023-04-03_224219080.png[04/Apr/2023 00:22:26] GET/todo/static/goods_images/image_2023-04-03_224219080.png HTTP/1.1"404 2355

model.py:

from django.db import models
class Good(models.Model):
name = models.CharField(max_length=100)
price = models.FloatField()
pic = models.ImageField(upload_to='todo/goods_images', null=True, blank=True)

class Meta:
ordering = ['-price']

def __str__ (self):
return str(self.name)

views.py:

from django.shortcuts import render
from django.views.generic.list import ListView
from .models import Good
class GoodsList(ListView):
model = Good
context_object_name = 'goods'
template_name = 'goods_list.html'

goods_list.html:

{% load static %}
<html>

{% for good in goods %}
<div>
{{ good.pic }}
<img src="{{ good.pic.url }}" />
{{ good.name }}
{{ good.price }}
</div>
{% endfor %}


</html>

settings.py:

from django.urls import path
from .views import GoodsList
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
path('goods_list/', GoodsList.as_view()),
]
if settings.DEBUG: 
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

已经讲过几个视频了但它们都是静态加载的只有一张图片所以在模板中写上它的确切路径但在我的例子中,我遍历了模型的所有实例以便在模板中使用变量

你在项目创建时没有这些设置,这很奇怪,但你需要在你的设置中:

STATIC_URL = '/static/' # Part of the url your server will understand as a static file request
MEDIA_URL = '/media/'# Part of the url your server will understand as a media file request
STATICFILES_DIRS = [
BASE_DIR / "static", # Adding the root static folder (if not set all the statics have to be in the apps)
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_assets') # Path to the folder where your static will be assembled on deployment in production (useless in dev)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Path to the folder where the uploaded files will be saved.

现在当你上传你的文件时,它们将会进入你的"upload_to"指定的子文件夹中的media文件夹属性。

最后加上这个:

urlpatterns += static。MEDIA_URL document_root = settings.MEDIA_ROOT)

:

urlpatterns += static。STATIC_URL document_root = settings.STATIC_ROOT)

在dev

中激活对媒体的访问

最新更新