You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django 4中如何展示数据库中的图片?

Django 4 首页展示数据库图片问题

我正在学习Django 4,这是我的第一个项目。已经搭建好项目并连接数据库,有一张图片和上传图片的表单,想在首页展示数据库里的所有图片,但不知道具体怎么实现。试了网上各种方法都没解决,求帮助。


项目配置

settings.py

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

urls.py

from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path("", views.products),
    path("sell/", views.sell),
    path("created/", views.created),
]

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

models.py

from django.db import models

class Product(models.Model):
    ...
    product_media = models.ImageField(upload_to="images", verbose_name="Фотографії товару")

views.py

from django.shortcuts import render
from .forms import SellForm
from .models import Product
from main.settings import MEDIA_URL, MEDIA_ROOT

def products(request):
    product_list = Product.objects.all()
    return render(request, "products.html", {"product_list": product_list, "media_url": MEDIA_URL, "media_root": MEDIA_ROOT})

products.html

<!DOCTYPE html>
<html lang="uk">
<head>
  <style>
   ...
  </style>
</head>
<body>

<h1>Оголошення </h1><a href="sell/">Створити нове оголошення</a>
{% if product_list %}
<table border="1">
    <tr>
        <th>Id</th>
        <th>Час створення</th>
        <th>Профіль продавця</th>
        <th>Ім'я продавця</th>
        <th>Прізвище продавця</th>
        <th>Телефон продавця</th>
        <th>Електронна пошта продавця</th>
        <th>Назва оголошення</th>
        <th>Опис</th>
        <th>Медіа</th>
    </tr>
    {% for object in product_list %}
    <tr>
        <td>{{ object.id }}</td>
        <td>{{ object.product_dt }}</td>
        <td>{{ object.product_username }}</td>
        <td>{{ object.product_name }}</td>
        <td>{{ object.product_lastname }}</td>
        <td>{{ object.product_phone }}</td>
        <td>{{ object.product_email }}</td>
        <td>{{ object.product_productname }}</td>
        <td>{{ object.product_description }}</td>
        <td><img src="{{object.product_media.url }}" alt="connect" /></td>   <!-- 此处我有疑问 -->
    </tr>
    {% endfor %}
</table>
{% else %}
Таблиця наразі пуста. Заповніть заявку вище.
{% endif %}
</body>
</html>

项目目录结构

├──application
│  ├──accounts
│  │  ├──__pycache__
│  │  ├──migrations
│  │  │  └──__pycache__
│  │  └──templates
│  ├──main
│  │  └──__pycache__
│  ├──media
│  │  └──images
│  ├──products
│  │  ├──__pycache__
│  │  ├──migrations
│  │  │  └──__pycache__
│  │  └──templates
│  ├──templates
│  │  └──registration
│  └──uploads

解决方案

1. 修复模板图片路径的容错处理

空的ImageField调用.url会直接报错,先给模板加判断逻辑:

<td>
  {% if object.product_media %}
    <img src="{{ object.product_media.url }}" alt="Товарне зображення" />
  {% else %}
    <span>Немає зображення</span>
  {% endif %}
</td>

2. 确认URL配置的层级

确保当前的urls.py是项目根目录下的配置文件,如果是app内的urls.py,需要在项目根urls.py中通过include引入:

# 项目根urls.py
from django.urls import path, include

urlpatterns = [
    path('', include('products.urls')),
    # 其他路由...
]

3. 简化视图变量传递

Django会自动处理媒体文件的URL拼接,不需要手动传递media_url和media_root,修改视图:

def products(request):
    product_list = Product.objects.all()
    return render(request, "products.html", {"product_list": product_list})

4. 检查表单上传逻辑

确保sell视图正确处理文件上传(必须接收request.FILES):

from django.shortcuts import redirect

def sell(request):
    if request.method == 'POST':
        form = SellForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('products')
    else:
        form = SellForm()
    return render(request, 'sell.html', {'form': form})

同时模板中的表单必须包含enctype="multipart/form-data":

<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Зберегти</button>
</form>

5. 验证文件存储与权限

  • 检查media/images目录是否存在,上传的图片是否实际保存在该路径下
  • 给media目录添加读写权限(Linux/macOS):
chmod -R 755 media/
  • 运行python manage.py makemigrations和python manage.py migrate同步模型变更

按以上步骤排查后,数据库中的图片应该能正常在首页显示。


内容的提问来源于stack exchange,提问作者derfacn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:40:32