首页 > 解决方案 > 如何在 Django 基本模板中呈现数据库查询集?

问题描述

我希望在我网站的所有页面上显示一些查询集。

从所有迹象来看,合乎逻辑的做法是将标记包含在 base.html 中。

不幸的是,base.html 没有被 url 呈现或调用。所以我很难做到这一点。

我做了什么。1

  1. 我在调用 reders index.html 的视图中进行了查询。
  2. 将查询集传递到上下文中。
  3. 在我的 index.html 模板中扩展 base.html
  4. 使用模板标记来调用查询集。

它在我当地运作良好。但是在部署到heroku后,它停止显示在我的索引上。

视图.py

from django.shortcuts import render, get_object_or_404
from .models import CompanyProfile, CompanyServices


def index_view(request):
    company_services = CompanyServices.objects.all()
    company_profile = CompanyProfile.objects.all()

    context = {
        'profile': company_profile,
        'services': company_services,
    }

    return render(request, 'webpages/index.html', context=context)

base.html 片段

<body>
  <!-- ======= Top Bar ======= -->
  <section id="topbar" class="d-none d-lg-block">
    <div class="container d-flex">
      <div class="contact-info mr-auto">
        <i class="icofont-envelope"></i><a href="mailto:contact@example.com">{{profile.company_email}}</a>
        <i class="icofont-phone"></i> {{profile.company_phone1}}
      </div>

我还能如何完成这项工作?

标签: django

解决方案


推荐阅读