我需要将数据放入侧边栏。除了 context_processors 之外,还没有找到其他解决方案。这是最干净、最理想的方法吗?
任何帮助都值得感激。我觉得有点奇怪,关于这个问题的信息这么难找。所以也许这对其他人也有帮助。
# animals/context_processors.py
from animals.models import Cows, Horses
from django.shortcuts import render
def allcows(request):
cows = Cows.objects.all()
return {"cows": cows}
def lasthorses(request):
horses = Horses.objects.all().order_by("-id")[:2]
return {"horses": horses}
Sidebar.html
<h1>Sidebar</h1>
<h3>All cows:</h3>
{%for cow in cows%}
<div>
The name is {{ cow.name }}, and the age of {{ cow.name}} is {{ cow.age }}.
</div>
{%endfor%}
<h3>last 2 horses:</h3>
{%for horse in horses%}
<div>
The name is {{ horse.name }}, and the age of {{ horse.name}} is {{ horse.age }}.
</div>
{%endfor%}
base.html
<body>
<div class="holy-grail-grid">
<header class="header">{% include 'animals/nav.html' %}
</header>
<main class="main-content">
<header id="main-header">
<h1>{% block main_heading %}Main Heading{% endblock %}</h1>
<h3> {% block header_content %}Heading{% endblock %}</h3>
</header>
{% block content %}
{% endblock %}
</main>
<section class="left-sidebar">
<p>My left sidebar{% include 'animals/sidebar.html' %}
</p>
</section>
<aside class="right-sidebar">
<p>My right sidebar{% include 'animals/justinfo.html' %}</p>
</aside>
<footer class="footer">
<p>The footer</p>
</footer>
</div>
</body>
如果您始终需要
cows
和horses
,则只需使用:并且由于
QuerySet
s 是懒惰的,如果您不需要cows
或horses
在您正在渲染的模板中,这将不会进行任何查询。