我需要将数据放入侧边栏中。除了 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
,您可以使用:
# animals/context_processors.py
from animals.models import Cows, Horses
from django.shortcuts import render
def all_animals(request):
cows = Cows.objects.all()
horses = Horses.objects.order_by('-id')[:2]
return {'cows': cows, 'horses': horses}
并且由于
QuerySet
是惰性的,因此如果您在渲染的模板中不需要 cows
或 horses
,则不会进行任何查询。
注意:通常 Django 模型会被赋予一个 singular 名称 [django-antipatterns],所以
而不是Cow
。Cows