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

使用Django如何遍历数据库所有条目并在HTML页面中以div元素展示

解决方法

第一步:修改视图函数获取全量数据

Django ORM 中 get() 方法仅能返回单个满足条件的对象,要获取表内所有条目,改用 all() 方法即可,修改后视图代码如下:

def gallery_view(request):
    # 按创建时间倒序获取所有画廊帖子,不需要排序可以删掉.order_by('-created_at')部分
    all_posts = GalleryPost.objects.all().order_by('-created_at')
    context = {
        'all_posts': all_posts
    }
    return render(request, "gallery.html", context)

注意:order_by 里的created_at 需替换为你自己模型中定义的时间字段,没有对应字段直接删除排序逻辑即可

第二步:在模板中遍历渲染内容

结合Bootstrap栅格系统做画廊展示的话,直接用Django模板语法的for循环遍历即可,示例模板代码:

{% extends 'base.html' %} <!-- 有公共基础模板的话保留这行 -->

{% block content %}
<div class="container mt-4">
  <h1>画廊页面</h1>
  <div class="row g-3">
    {% for post in all_posts %}
    <div class="col-12 col-md-6 col-lg-4">
      <div class="card h-100">
        <!-- 以下字段替换为你GalleryPost模型中定义的实际字段 -->
        <img src="{{ post.cover.url }}" class="card-img-top" alt="{{ post.title }}">
        <div class="card-body">
          <h5 class="card-title">{{ post.title }}</h5>
          <p class="card-text">{{ post.description }}</p>
        </div>
      </div>
    </div>
    <!-- 空数据兜底提示 -->
    {% empty %}
    <div class="col-12">
      <p class="text-center text-muted">当前暂无画廊内容</p>
    </div>
    {% endfor %}
  </div>
</div>
{% endblock %}
  • 模板中使用的字段名必须和你GalleryPost模型定义的字段完全一致,否则会触发渲染错误
  • 如果用到图片资源,需要提前配置好Django的媒体文件存储和访问规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:15:03